How to Use Call Apply and Bind in JavaScript
How to Use Call Apply and Bind in JavaScript
name:,
surname:,
getFullName: (){
.log(.name++.surname);
}
}
(); 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. obj2 = {
name:,
surname:
}
(); You can also pass different arguments in the call() function along with the object. obj = {
name:,
surname:,
getFullName: (){
.log(.name++.surname++age++gender);
}
(, 21, "");
name:,
surname:,
getFullName: (){
.log(.name++.surname++age++gender);
}
}
(, ]);
âââââ
name:,
surname:,
getFullName: (){
.log(.name+.surname);
}
}
obj2 = {
name:,
surname:
}
func = obj.getFullName.bind(obj2);
func();
MUO
How to Use Call Apply and Bind in JavaScript
JavaScript call(), apply(), and bind() stand a decent chance of showing up in your web dev interview. Are you prepared? 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. obj = {name:,
surname:,
getFullName: (){
.log(.name++.surname);
}
}
(); 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. obj2 = {
name:,
surname:
}
(); You can also pass different arguments in the call() function along with the object. obj = {
name:,
surname:,
getFullName: (){
.log(.name++.surname++age++gender);
}
(, 21, "");
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: obj = {name:,
surname:,
getFullName: (){
.log(.name++.surname++age++gender);
}
}
(, ]);
âââââ
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: obj = {name:,
surname:,
getFullName: (){
.log(.name+.surname);
}
}
obj2 = {
name:,
surname:
}
func = obj.getFullName.bind(obj2);
func();