使用 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,4,5,6,1,2,3,4,5,6
我非常怀疑我已经发现了一个错误,但很困惑为什么它会这样工作,为什么要以这种方式再次附加参数。使困惑
Reading through the source at:
http://documentcloud.github.com/underscore/underscore.js
This is the _bind method so frequently used (I've removed the native check for clarity)
_.bind = function(func, obj) {
var args = slice.call(arguments, 2);
return function() {
return func.apply(obj, args.concat(slice.call(arguments)));
};
};
The args that get passed func.apply seems unnecessarily duplicated at the end
An example using Node interpreter (remove last line to try in Firebug etc..)
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);
This outputs:
3,4,5,6,1,2,3,4,5,6
I highly doubt I've found a bug but confused as to why its working this way, why append the args again in such fashion. Confused
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
bind 方法返回一个闭包,它可以接受传递给函数的附加参数。下划线代码中对
arguments
的两次引用并不引用同一组参数。第一个来自封闭函数,第二个来自返回的闭包。下面是这个方法的一个稍微修改过的版本,希望它能更清楚地说明这一点:这本质上允许您在绑定到对象时柯里化一个方法。其用法的一个例子是:
The bind method returns a closure, which can accept additional arguments to be passed to the function. The two references to
arguments
in the underscore code do not refer to the same set of arguments. The first is from the enclosing function, and the second is from the returned closure. Here is a slightly modified version of this method, which hopefully makes it clearer:This essentially allows you to curry a method when it is bound to an object. An example of its usage would be:
对
_bind
的调用将对象和一些参数绑定到方法。调用绑定方法时,您可以将其他参数传递给它。您不太可能两次传递相同的参数。用法是:The call to
_bind
binds an object and some arguments to a method. You can pass additional arguments to the bound method when you invoke it. You wouldn't likely pass the same arguments twice. Usage is: