How to Use Call Apply and Bind in JavaScript

How to Use Call Apply and Bind in JavaScript

How to Use Call Apply and Bind in JavaScript

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();

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?

Share:
0 comments

Comments (0)

Leave a Comment

Minimum 10 characters required

* All fields are required. Comments are moderated before appearing.

No comments yet. Be the first to comment!

How to Use Call Apply and Bind in JavaScript | Trend Now