如果我想部分应用一个函数,我可以使用bind
,但似乎我必须影响函数的接收者(bind
的第一个参数)。这是正确的吗?
我想使用bind
执行部分应用而不影响接收者。
myFunction.bind(iDontWantThis, arg1); // I dont want to affect the receiver
最佳答案
partial application using
bind
without affecting the receiver
这是不可能的。 bind
被明确设计为部分应用“第零个参数” - this
值,以及可选的更多参数。如果您只想修复函数的第一个(可能还有更多)参数,但不绑定(bind) this
,则需要使用不同的函数:
Function.prototype.partial = function() {
if (arguments.length == 0)
return this;
var fn = this,
args = Array.prototype.slice.call(arguments);
return function() {
return fn.apply(this, args.concat(Array.prototype.slice.call(arguments)));
};
};
当然,很多库也提供这样的功能,例如Underscore , Lodash , Ramda等等。但是没有本地等效项。
关于javascript - 使用bind进行部分应用而不影响接收者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28744753/