5
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?

1
  • 2
    When you want to pass the bound function to something else. Commented Apr 6, 2013 at 20:18

1 Answer 1

12

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));
Sign up to request clarification or add additional context in comments.

1 Comment

Was very nooby of me, but creating this fiddle based on your example helped me clear the idea. Thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.