Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use Function.prototype.bind instead of Function.prototype.call?

Tags:

javascript

myFunction.call(thisArg, arg1, arg2 ...)

My understanding is that when I use call method and provide a thisArg the this value in the function is set to object I pass in.

myFunction.bind(thisArg, arg1, arg2 ...)

And the bind method on the other hand returns a new function with the context of this of the new function set to the object I pass in.

But what I don't understand is why use bind instead of a call. If all I want to do is change the context of this, call seems sufficient to me. Then why use bind when it breaks in browsers IE8 and below.

So, when does using bind become a better case compared to call?

like image 255
nimgrg Avatar asked Apr 06 '13 20:04

nimgrg


1 Answers

When does using bind become a better case compared to call?

Callbacks.

If you need to make sure that a function is called in the context of a particular object, but have no controll of how the function is called (such as when you pass a function as a parameter to a callback), you'd use bind.

var f,
    example;
f = new Foo();
example = document.getElementById('example');

//`f.bar` is called in the context of `f`
f.bar();

//`f.bar` will be called in the context of `example`
example.addEventListener('click', f.bar); 

//`f.bar` will be called in the context of `f`
example.addEventListener('click', f.bar.bind(f));
like image 179
zzzzBov Avatar answered Oct 04 '22 06:10

zzzzBov