2013-04-06 21 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

相關問題