由于 bind
函数不是一个跨浏览器(旧版本)的函数,因此需要使用它的 polyfill:(来自 John Resig 的书籍)
/*1*/ Function.prototype.bind = function ()
/*2*/ {
/*3*/ var fn = this,
/*4*/ args = Array.prototype.slice.call(arguments),
/*5*/ object = args.shift();
/*6*/ return function ()
/*7*/ {
/*8*/ return fn.apply(object,
/*9*/ args.concat(Array.prototype.slice.call(arguments)));
/*10*/ };
/*11*/ };
但我不明白为什么在第 #9
行需要使用 arguments
。
我的意思是:
如果我有这个对象:
var foo = {
x: 3
}
我有这个函数:
var bar = function(p,b){
console.log(this.x+' '+p+' '+b);
}
所以,如果我想让bar
在foo
上下文中运行,带有参数 - 我需要做的就是:
var boundFunc = bar.bind(foo,1,2)
boundFunc ()...
当我运行var.bind(foo,1,2)
时,arguments
为[object Object],1,2
。
这些参数保存在第4行。
很好。
现在,bind
函数返回其自身的封闭函数:
function ()
{
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
}
问题
为什么我们需要在这里使用 arguments
?似乎他们是用于像这样的某些东西:
var boundFunc = bar.bind(foo,1,2)
boundFunc (more1,more2....) //<----- ??
我有什么疏漏吗?
当我设置第一个var boundFunc = bar.bind(foo,1,2)
时,我已经声明了参数。为什么我们需要再次声明它们?
someData
)。因此,当事件处理程序被调用并传递事件对象时,绑定的函数将作为第二个参数接收它。如果您还没有阅读过部分应用程序文章,请阅读它,它应该会使事情更加清晰。 - Felix Kling