来自 prototype.js 的 bind() 代码


Function.prototype.bind = function(){
  var fn = this, 
      // clone arguments
      args = Array.prototype.slice.call(arguments), 
      // get the first argument, which should be an object, and args will be modified. 
      object = args.shift();
  return function(){
    return fn.apply(object,
      // why use concat??? why? 
      args.concat(Array.prototype.slice.call(arguments)));
  };
};
...
elem.onclick = Button.click.bind(Button, false);
....

我从这里看到了上面的代码:http://ejohn.org/apps/learn/#86在学习JavaScript时。该代码摘自原型.js。注释是我添加的,而不是来自原始代码。

我的问题是为什么要使用args.concat(Array.prototype.slice.call(arguments)))?我认为通过参数就足够了。原型.js中的 bind() 必须有其正当理由。请帮助我理解它。谢谢!

好吧,您还希望能够访问传递给绑定函数的参数,而不仅仅是绑定到该函数的参数。

args 是指传递给 .bind 的参数,arguments 是指传递给绑定函数(由 .bind 返回的参数)。

.bind进行更改,并使用以下函数比较版本:

function foo() {
    console.log(arguments);
}
var bound = foo.bind(null, 1, 2);
bound(3, 4);

使用 args.concat(Array.prototype.slice.call(arguments))); ,输出将是

[1, 2, 3, 4]

只有args,它将是

[1, 2]

对于事件处理程序,如果仅使用 args ,则无法访问传递给它的事件对象。

最新更新