Function.bind 返回一个新函数,当调用该函数时,将始终使用绑定上下文调用原始函数。
可以像这样实现 Function.bind :
Function.prototype.bind = function(context) {
var origFunction = this;
return function() {
return origFunction.apply(context, arguments);
};
};
你可以在这里试试这个:http: //jsfiddle.net/HeRU6/
所以当你这样做时somefunction.bind("foo")
,它会返回一个新函数。调用这个新函数将始终作为上下文调用somefunction
。"foo"
您可以编写一个只绑定参数而不绑定上下文的函数:
Function.prototype.curry = function() {
var origFunction = this, args = Array.prototype.slice.call(arguments);
return function() {
console.log(args, arguments);
return origFunction.apply(this, Array.prototype.concat.apply(args, arguments));
};
};
a = function() { console.log(this, arguments); };
b = a.curry(1, 2);
b(); // Window [1, 2]
b(3); // Window [1, 2, 3]
b.call("foo", 4); // "foo" [1, 2, 4]