JavaScript Bind and Apply/Call Method<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

JavaScript Bind and Apply/Call Method

Posted on: May 29, 2017

JavaScript has three methods that are useful to assign on what this refer to. These three methods are Bind, Apply and Call.

Bind are from the prototype of Function. It takes as first parameter the reference to this, and all the subsequent parameters to be the argument to the function. The Bind method return a copy of the function with this one having the this to the one desired.

Call is similar, but instead of returning a copy with the provided reference to this, it provides the this reference and invoke the method.

Apply is like call but the second parameter is an array instead of being a signature with undermined amount of parameter.

Here is an example to distinct the difference:, param1, param2, param3);
2// or
3f1.apply(myThisRef, [param1, param2, param3]);

How can this be useful? This can be useful to change the context of a piece of code to access different member without assigning the values. For example, in the following code we have the same function and by calling apply or bind we can assign this to a complete new object that has what is using by this, in that case the_name.

1var hero = {
2 _name: "John Doe",
3 getName: function () {
4 return this._name;
5 },
8console.log(hero.getName()); // John Do
9// --- var
10hero2 = { _name: "Patrick" };
11var getNameMethod = hero.getName;
13console.log(getNameMethod.apply(hero2)); // Patrick
14console.log(getNameMethod.bind(hero2)()); // Patrick

This example illustrates that apply can be called to have momentary a call with a reference to the hero2 instead of the original hero. On the next line, the bind method is called and executed by using the parentheses right away. Normally, we would store the return value of the bind method to get an object that can get subsequent calls with the hero2 this reference.

When to use of of the other? apply and call should be used when it's only for one invocation. Bind should be used to store the new variable with that will have a this with the provided reference to this when created with bind.