如果我想部分应用一个函数,我可以使用bind
,但似乎我必须影响函数的接收者(第一个参数bind
)。它是否正确?
我想使用执行部分应用程序bind
而不影响接收器。
myFunction.bind(iDontWantThis, arg1); // I dont want to affect the receiver
部分应用使用bind
不影响接收器
那是不可能的。bind
被明确设计为部分应用“第零参数” -this
值,以及可选的更多参数。如果您只想修复函数的第一个(以及可能更多)参数,但保留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)));
};
};
当然,很多库也提供这样的功能,例如下划线, Lodash, Ramda等等。但是没有本地等效项。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)