我试图用柯里化(Currying)来增强函数原型(prototype),但我得到了意想不到的结果。它在某些情况下工作正常,但并非全部。
这是我使用原型(prototype)增强的代码:
Function.prototype.method = function(name, func) {
if(!this.prototype[name]){
this.prototype[name] = func;
}
return this;
};
Function.method("curry-left", function(){
var slice = Array.prototype.slice;
var that = this;
var args = slice.call(arguments,0);
return function(){
that.apply(null, args.concat(slice.call(arguments,0)));
}
});
我使用以下代码对其进行测试:
function print(arg1, arg2){
console.log(arg1 + ", " + arg2);
}
print["curry-left"]("hej")("då"); // prints hej, då
var op = {"+":function(a,b){return a + b;}}
console.log(op["+"]["curry-left"](1)(2)) // prints undefined
我尝试过调试它,似乎原型(prototype)中的 that
变量把一切搞乱了,但我不确定为什么。如果我执行 console.log(that)
我会得到 [Function]
结果,这似乎是正确的
如果我能让它在两个实例上工作,那就太好了。
提前致谢
最佳答案
问题是你的内部函数不返回结果:
Function.method("curry-left", function(){
var slice = Array.prototype.slice;
var that = this;
var args = slice.call(arguments,0);
return function(){
that.apply(null, args.concat(slice.call(arguments,0)));
^
}
});
修复:
return that.apply(null, args.concat(slice.call(arguments,0)));
关于Javascript部分应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24465569/