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]

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...