微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JavaScript – 使用Bind下划线行为

阅读来源:
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)));
    };
  };

获得通过func.apply的参考结果似乎不必要地重复

使用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);

输出

3,6,1,6

我非常怀疑我发现了一个错误,但是为什么以这种方式工作,为什么再以这种方式再次添加这些参数呢?困惑

解决方法

bind方法返回一个闭包,它可以接受传递给函数的其他参数.对下划线代码中的参数的两个引用不引用相同的参数集.第一个来自封闭函数,第二个来自返回的闭包.这是这个方法一个稍微修改的版本,希望能够更清楚:
_.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));

  }

这实际上允许您在绑定到对象时咖喱一种方法.其使用的一个例子是:

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

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

>>> myObj.newFunc(4,6);
[1,6]

原文地址:https://www.jb51.cc/js/151249.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐