【问题标题】:bind() code from prototype.js来自prototype.js 的bind() 代码
【发布时间】:2013-12-19 05:10:45
【问题描述】:
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。 cmets 由我添加,而不是来自原始代码。

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

【问题讨论】:

    标签: javascript prototypejs


    【解决方案1】:

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

    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,您将无法访问传递给它的事件对象。

    【讨论】:

    • 谢谢!你的最后一句话对我帮助很大。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 2012-03-26
    • 2013-06-23
    • 1970-01-01
    相关资源
    最近更新 更多