我必须编写一个柯里化(Currying)函数,它接受一个函数,执行另一个函数,然后通过将最后一个参数作为计算值来执行第二个函数。
我遇到的问题:如何同时访问第一个函数和最后的值?
到目前为止,我可以通过在函数语法中编写一个函数并访问 this 来访问第一个函数。
Function.prototype.foo = function(x) {
// can't make currying functions by using functions keyword
console.log(this, x);
};
(() => 10).foo(1);
当我编写柯里化(Currying)函数时,我可以访问第二个 (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 关键字创建柯里化(Currying)函数:
Function.prototype.bar = function(x) {
return function(y) {
console.log(x, y)
}
}
我无法真正验证这是否有效:
(function() {return 10}).bar(1)(2)
在任何情况下,ˋthisˋ都是函数,而不是返回值 (10),因为函数未被调用。
关于javascript - 如何在柯里化(Currying)函数中访问前一个函数的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56003110/