使用Bind强调行为

9 javascript underscore.js

阅读源代码:http: //documentcloud.github.com/underscore/underscore.js

这是经常使用的_bind方法(为了清楚起见,我删除了本机检查)

   _.bind = function(func, obj) {
    var args = slice.call(arguments, 2);
    return function() {
      return func.apply(obj, args.concat(slice.call(arguments)));
    };
  };
Run Code Online (Sandbox Code Playgroud)

通过func.apply传递的args似乎在最后不必要地重复

使用Node解释器的示例(删除最后一行以在Firebug等中尝试..)

var arguments = [1,2,3,4,5,6];
var args = Array.prototype.slice.call(arguments, 2);
var appliedArgs = args.concat(Array.prototype.slice.call(arguments));
require('sys').puts(appliedArgs);
Run Code Online (Sandbox Code Playgroud)

这输出:

3,4,5,6,1,2,3,4,5,6
Run Code Online (Sandbox Code Playgroud)

我非常怀疑我发现了一个错误,但是为什么它以这种方式工作很困惑,为什么再次以这种方式附加args.困惑

Gar*_*ers 16

bind方法返回一个闭包,它可以接受要传递给函数的其他参数.arguments下划线代码中的两个引用不引用同一组参数.第一个来自封闭函数,第二个来自返回的闭包.这是这个方法的略微修改版本,希望它更清晰:

_.bind = function(func, obj /*, arg1, arg2 ... argN */) {

  // Prepare default arguments for currying, removing
  // the function and object references
  var args = Array.prototype.slice.call(arguments, 2);

  // Return a closure that has access to the parent scope
  return function(/* arg1, arg2 ... argN */) {

    // Prepare arguments that are passed when bound
    // method is called
    var args2 = Array.prototype.slice.call(arguments);

    // Curry the method with the arguments passed
    // to the enclosing function and those passed
    // to the bound method
    return func.apply(obj, args.concat(args2));

  }
Run Code Online (Sandbox Code Playgroud)

这基本上允许您在方法绑定到对象时对其进行curry.其用法的一个例子是:

var myObj = {},
    myFunc = function() {
      return Array.prototype.slice.call(arguments);
    };

myObj.newFunc = _.bind(myFunc, myObj, 1, 2, 3);

>>> myObj.newFunc(4, 5, 6);
[1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

  • 没问题.如果您想要了解Underscore源代码,他们还会提供带注释的版本 - http://documentcloud.github.com/underscore/docs/underscore.html (2认同)