2013-04-06 19 views
5
myFunction.call(thisArg, arg1, arg2 ...) 

我的理解是,当我使用call方法,并提供在功能thisArgthis值设置为对象我传递英寸为什么要使用Function.prototype.bind而不是Function.prototype.call?

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

而在另一方面bind方法返回一个新随着新功能设置的this给我传递。

但我不明白的是为什么要使用bind代替call的对象的上下文功能。如果我只想改变this的环境,call对我来说似乎就足够了。那么为什么在浏览器IE8和更低版本中使用绑定呢?

那么,什么时候使用bind成为比call更好的情况呢?

+2

当你想绑定的功能传递给别的东西。 – 2013-04-06 20:18:31

回答

12

call相比,何时使用bind变得更好?

回调。

如果你需要确保一个函数被调用特定对象的情况下,但没有的功能是如何调用控制研究(例如,当你将一个函数作为参数传递给回调),你'使用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)); 
+2

对我来说是非常nooby,但根据你的例子创建这个[小提琴](http://jsfiddle.net/JZ6aS/9/)帮助我清除了这个想法。谢谢!! – nimgrg 2013-04-06 20:59:31

+0

小提琴帮助我澄清了thx – jamie 2014-12-12 18:29:55

相关问题