You may have come across various built-in functions like those for arrays and strings while practicing JavaScript. While you might use these more common methods in your day-to-day programming tasks, other methods can be used for special purposes.JavaScript's call(), apply(), and bind() are some such methods that have their special use-cases and are often used to test your JavaScript knowledge in coding interviews. Let's take a closer look at how you can use them.
1. call()call() allows for a function or method belonging to one object to be assigned and called for a different object. You can refer to the values of the object by using the this keyword.
Check out this call() example.
let obj = {
name:"John",
surname:"Doe",
getFullName: function(){
console.log(this.name+" "+this.surname);
}
}
obj.getFullName();
The object obj has a function named getFullName() that prints the full name of the person. Now, if you want to use getFullName() with a different object that has different values, you can do so using the call() function.
const obj2 = {
name:"Jane",
surname:"Doe"
}
obj.getFullName.call(obj2);
You can also pass different arguments in the call() function along with the object.
let obj = {
name:"John",
surname:"Doe",
getFullName: function(age, gender){
console.log(this.name+" "+this.surname+" "+age+" "+gender);
}
obj.getFullName.call(obj2, 21, "female");
2. apply()
The apply() function works similar to call() function. The only difference between the call() and apply() function is you can pass multiple parameters in the array and use them.
Here's an apply() example:
const obj = {
name:"John",
surname:"Doe",
getFullName: function(age, gender){
console.log(this.name+" "+this.surname+" "+age+" "+gender);
}
}
obj.getFullName.apply(obj2, [21, "female"]);
Related: JavaScript Array Methods You Should Master Todayââââââ
3. bind()bind() returns the exact copy of a function and binds it with an object. This method is used to bind and keep a copy of a method and use it later. You can use the function whenever you want by invoking it.
Here's a bind() example:
const obj = {
name:"John",
surname:"Jane",
getFullName: function(){
console.log(this.name+this.surname);
}
}
const obj2 = {
name:"Jane",
surname:"Doe"
}
let func = obj.getFullName.bind(obj2);
func();
Never Stop Learning JavaScript
The call(), apply(), and bind() functions are important when it comes to prepping for JavaScript interviews. There's a myriad of other core concepts in JavaScript that you should master to become the most efficient programmer you can be; why not start with array methods?
Close