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

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

I understand that when I use a method calland provide a thisArgvalue thisin a function, it is set for the object to which I pass.

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

And the method bind, on the other hand, returns a new function with the context of the thisnew function set for the object to which I am passing.

But I do not understand why to use bindinstead call. If all I want to do is change the context this, callit seems to me sufficient. Then why use bind when it breaks in IE8 and below browsers.

So, when does usage bindbecome a better case compared to call?

+5
source share
1 answer

When bindwill use be a better case compared to call?

Callbacks

If you need to make sure that the function is called in the context of a specific object, but does not have control over how the function is called (for example, when you pass the function as a parameter for a callback) 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));
+12
source

All Articles