关于prototype.js函数绑定代码的解释

res*_*ion 1 javascript jquery resig prototypejs

来自:http://ejohn.org/apps/learn/#2

Function.prototype.bind = function(){
  var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift();
  return function(){
    return fn.apply(object,
      args.concat(Array.prototype.slice.call(arguments)));
  };
};
Run Code Online (Sandbox Code Playgroud)

谁能告诉我为什么第二次返回是必要的(在fn.apply之前)?

还有,谁能解释为什么args.concat是必要的?为什么不重写为:

fn.apply(object, args)
Run Code Online (Sandbox Code Playgroud)

代替

return fn.apply(object,
          args.concat(Array.prototype.slice.call(arguments)));
Run Code Online (Sandbox Code Playgroud)

Anu*_*rag 7

第二次返回是必要的,否则我们将失去绑定函数的任何返回值.

你可能已经知道这一点,但不要伤害提及.如果我们不在fn.apply另一个函数中包装,那么我们直接调用fn次优的函数,因为bind它只应该设置执行上下文(应该this在函数内部引用),而不是调用它.

可以通过调用它们上的callor apply方法来调用Javascript方法.这是一个小例子:

function example() {
    alert("useless example");
}

example.apply() // or example.call(), alerts "useless example";
Run Code Online (Sandbox Code Playgroud)

Prototype的bind()中的外部函数应该像绑定函数周围的隐形包装一样工作.因此,传递给包装器的任何参数也应该传递给绑定函数,并且它必须返回绑定函数返回的任何值,这就是返回语句存在的原因.

在fn.apply中进行args.concat的原因是不同的,它不是可选的.bind在Prototype中,您可以在绑定函数前添加参数.

args表示我们调用bind函数时传递的参数.arguments表示我们调用绑定函数时传递的参数.我们基本上在那里连接两个数组.

从上面的例子:

var obj = { x: 'prop x' };
var boundExample = example.bind(obj, 12, 23); // args => 12, 23
boundExample(36, 49); // arguments => 36, 49

// arguments that our example() function receives => 12, 23, 36, 49
Run Code Online (Sandbox Code Playgroud)