最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why use Function.prototype.bind instead of Function.prototype.call? - Stack Overflow

programmeradmin4浏览0评论
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?

Share Improve this question edited Apr 11, 2013 at 13:58 nimgrg asked Apr 6, 2013 at 20:10 nimgrgnimgrg 5821 gold badge7 silver badges18 bronze badges 1
  • 2 When you want to pass the bound function to something else. – Paul Grime Commented Apr 6, 2013 at 20:18
Add a ment  | 

1 Answer 1

Reset to default 12

When does using bind bee a better case pared 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));
发布评论

评论列表(0)

  1. 暂无评论