如何在柯里化函数中访问前一个函数的结果?
How can I access the result from a previous function in a currying function?
我必须编写一个柯里化函数,它接受一个函数,执行另一个函数,然后通过将最后一个参数作为计算值来执行第二个函数。
我遇到的问题:如何同时访问第一个函数和最后的值?
到目前为止,我可以通过在函数语法中编写一个函数并访问 this 来访问第一个函数。
Function.prototype.foo = function(x) {
// can't make currying functions by using functions keyword
console.log(this, x);
};
(() => 10).foo(1);
当我编写柯里化函数时,我可以访问第二个 (x) 和第三个 (y) 函数。
Function.prototype.bar = x => y => {
// but also can't access this like in function syntax
console.log(x, y);
}
// how would I access 10 in bar?
(() => 10).bar(1)(2);
最终的函数看起来像这样:
someFunc.then(someSecondFunc).then(someThirdFunc)(100)
非常感谢您的帮助!
不确定它是否能解决您的问题,但您可以使用 function 关键字创建柯里化函数:
Function.prototype.bar = function(x) {
return function(y) {
console.log(x, y)
}
}
我无法真正验证这是否有效:
(function() {return 10}).bar(1)(2)
在任何情况下,ˋthisˋ都是函数,而不是 return 值 (10),因为函数未被调用。
通过使用柯里化函数和 function 关键字,我的答案如下所示:
Function.prototype.then = function(secondFct) {
const firstFct = this;
return function(value) {
return firstFct(secondFct(value));
}
}
非常感谢 buboh 的帮助。
我必须编写一个柯里化函数,它接受一个函数,执行另一个函数,然后通过将最后一个参数作为计算值来执行第二个函数。
我遇到的问题:如何同时访问第一个函数和最后的值?
到目前为止,我可以通过在函数语法中编写一个函数并访问 this 来访问第一个函数。
Function.prototype.foo = function(x) {
// can't make currying functions by using functions keyword
console.log(this, x);
};
(() => 10).foo(1);
当我编写柯里化函数时,我可以访问第二个 (x) 和第三个 (y) 函数。
Function.prototype.bar = x => y => {
// but also can't access this like in function syntax
console.log(x, y);
}
// how would I access 10 in bar?
(() => 10).bar(1)(2);
最终的函数看起来像这样:
someFunc.then(someSecondFunc).then(someThirdFunc)(100)
非常感谢您的帮助!
不确定它是否能解决您的问题,但您可以使用 function 关键字创建柯里化函数:
Function.prototype.bar = function(x) {
return function(y) {
console.log(x, y)
}
}
我无法真正验证这是否有效:
(function() {return 10}).bar(1)(2)
在任何情况下,ˋthisˋ都是函数,而不是 return 值 (10),因为函数未被调用。
通过使用柯里化函数和 function 关键字,我的答案如下所示:
Function.prototype.then = function(secondFct) {
const firstFct = this;
return function(value) {
return firstFct(secondFct(value));
}
}
非常感谢 buboh 的帮助。