我在Stack Overflow和网络上搜索,但没有找到关于这三种方法之间区别的合适结果或解释。
据我理解,它们都执行相同的函数/方法
,只是在不同的上下文中执行。
var google = {
makeBeer : function(arg1,arg2){
alert([arg1, arg2]);
}
}
google.makeBeer('water','soda');
这是我对Google对象的常规函数。现在当我在这里使用call和bind方法时,输出如下。
var google = {
makeBeer: function (arg1, arg2) {
alert([arg1, arg2]);
}
}
google.makeBeer('water', 'soda');
function yahoo() {}
var yah = new yahoo();
google.makeBeer.call(yah, 'pepsi', 'coke');
function msn() {
}
var msn = new msn();
google.makeBeer.call(msn, 'sprite', 'limca');
我仍然不明白为什么要这样做,我可以继续调用google.makeBeer
三次并使用不同的参数。
有谁能更详细地给我解释一下吗?
google.makeBeer
没有使用this
。当以google.makeBeer(...);
的形式调用时,函数内部的this
将引用google
。当以google.makeBeer.call(yah, ...);
的形式调用时,this
将引用yah
。bind
实际上并不执行函数,它创建一个新函数,其中this
和可选的一些参数绑定到传递的参数上。请参见 https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this 和 https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind。 - Felix Kling.call()
和.apply()
之间的主要区别在于可以传递的参数数量(一个只允许一个,另一个允许更多)。我不确定.bind()
的参考是什么,但它通常指事件及其处理程序被“绑定”。 - Jared Farrish