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
bee a better case pared to call
?
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
bee a better case pared to call
?
- 2 When you want to pass the bound function to something else. – Paul Grime Commented Apr 6, 2013 at 20:18
1 Answer
Reset to default 12When does using
bind
bee a better case pared 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));