来自prototype.js的bind()代码

时间:2013-12-19 05:10:46

标签: javascript prototypejs

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。该代码摘自prototype.js。评论由我添加,而不是原始代码。

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

1 个答案:

答案 0 :(得分:4)

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

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,则在事件处理程序的情况下,您将无法访问传递给它的事件对象。