Javascript 用Bind下划线行为
阅读以下来源: 这是经常使用的_bind方法(为了清晰起见,我删除了本机检查) 通过func.apply的参数在最后似乎不必要地重复 使用节点解释器的示例(删除最后一行以尝试Firebug等) 这将产生:Javascript 用Bind下划线行为,javascript,underscore.js,Javascript,Underscore.js,阅读以下来源: 这是经常使用的_bind方法(为了清晰起见,我删除了本机检查) 通过func.apply的参数在最后似乎不必要地重复 使用节点解释器的示例(删除最后一行以尝试Firebug等) 这将产生: 3,4,5,6,1,2,3,4,5,6 我非常怀疑我已经发现了一个bug,但是对于它为什么会这样工作,为什么还要以这样的方式再次附加args感到困惑。bind方法返回一个闭包,它可以接受传递给函数的附加参数。下划线代码中对参数的两个引用不引用同一组参数。第一个来自封闭函数,第二个来自返回的
3,4,5,6,1,2,3,4,5,6
我非常怀疑我已经发现了一个bug,但是对于它为什么会这样工作,为什么还要以这样的方式再次附加args感到困惑。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, 1, 2, 3);
>>> myObj.newFunc(4, 5, 6);
[1, 2, 3, 4, 5, 6]
调用
\u bind
将对象和一些参数绑定到方法。在调用绑定方法时,可以将其他参数传递给该方法。你不可能两次传递相同的论点。用途是:
function sum() {
var total = 0;
for (var i=0; i < arguments.length; ++i) {
total += arguments[i];
}
return total;
}
var sumsome = _bind(sum, {}, 1, 2, 3);
sumsome(4,5,6); // equivalent to the call ({summ: sum}).summ(1,2,3,4,5,6)
sumsome('a','b','c'); // equivalent to the call ({summ: sum}).summ(1,2,3,'a','b','c')
函数和(){
var合计=0;
对于(变量i=0;i
谢谢gary。我错过了,现在说得通了,没问题。如果您试图了解下划线源代码,它们还提供了一个带注释的版本-
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]
function sum() {
var total = 0;
for (var i=0; i < arguments.length; ++i) {
total += arguments[i];
}
return total;
}
var sumsome = _bind(sum, {}, 1, 2, 3);
sumsome(4,5,6); // equivalent to the call ({summ: sum}).summ(1,2,3,4,5,6)
sumsome('a','b','c'); // equivalent to the call ({summ: sum}).summ(1,2,3,'a','b','c')