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
?
When does using
bind
become a better case compared tocall
?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With