JavaScript call vs bind vs apply

All these methods are used for similar use but with very small difference.They are used to set the context (i.e set which object will be bound to this)during a function call.

bind() – Problem 1

var user = {
    data        :[
        {name:"T. Woods", age:37},
        {name:"P. Mickelson", age:43}
    ],
    clickHandler:function (event) {
        $ ("input").val (this.data[0].name + " " + this.data[0].age);
    }

}

// Assign an eventHandler to the button's click event​
$ ("button").click (user.clickHandler);

When you click the button, you get an error because this in the clickHandler () method is bound to the button HTML element, since that is the object that the clickHandler method is executed on.

Solution :

$ ("button").click (user.clickHandler.bind (user));

Problem 2

// This data variable is a global variable​
var data = [
    {name:"Samantha", age:12}
]

var user = {
    // local data variable​
    data    :[
        {name:"T. Woods", age:37}
    ],
    showData:function (event) {
        console.log (this.data[0].name + " " + this.data[0].age);
    }

}

// Assign the showData method of the user object to a variable​
var showDataVar = user.showData;

showDataVar (); // Samantha 12 (from the global data array, not from the local data array)​

This happens because showDataVar () is executed as a global function and use of this inside showDataVar () is bound to the global scope, which is the window object in browsers.

Solution :

// Bind the showData method to the user object​
var showDataVar = user.showData.bind (user);

// Now the we get the value from the user object because the this keyword is bound to the user object​
showDataVar (); // P. Mickelson 43​

apply() vs call() vs bind()

The apply and call methods are almost identical when setting the this value except that you pass the function parameters to apply () as an array, while you have to list the parameters individually to pass them to the call () method.

They can be used for method borrowing

call()

var anArrayLikeObj = {0:"Martin", 1:78, 2:67, 3:["Letta", "Marieta", "Pauline"], length:4 };
var newArray = Array.prototype.slice.call(anArrayLikeObj , 0);
console.log (newArray);  //["Martin", 78, 67, Array[3]

This could have also done with bind and apply

apply() 

var newArray = Array.prototype.slice.apply(anArrayLikeObj , [0]);
console.log (newArray);  //["Martin", 78, 67, Array[3]

bind()

var newArray = Array.prototype.slice.bind(anArrayLikeObj , 0);
console.log (newArray); //function b()

This is the main difference between these three functions – 

apply takes array as argument list

Call takes simple list of arguments

Both call and apply returns value whereas bind returns function that has to be invoked.


call() vs apply()

Call can be used for  variable-arity, also known as variadic functions.
These are functions that accept any number of arguments instead of a fixed number of arguments.

var allNumbers = [23, 11, 34, 56];
// We cannot pass an array of numbers to the Math.max method like this​
console.log (Math.max (allNumbers)); // NaN
var allNumbers = [23, 11, 34, 56];
// Using the apply () method, we can pass the array of numbers:​
console.log (Math.max.apply (null, allNumbers)); // 56

Well I guess the differences are pretty clear now.


References

JavaScriptIsSexy Call Apply Bind

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s