JavaScript   发布时间:2022-04-16  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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]

大佬总结

以上是大佬教程为你收集整理的JavaScript – 使用Bind下划线行为全部内容,希望文章能够帮你解决JavaScript – 使用Bind下划线行为所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。