以下代码运行良好:
// Returns a function that inherits parent's scope
const curry = argOne => argTwo => console.log(argOne, argTwo);
const initiateFunction = curry(1);
initiateFunction(2) // Outputs: "1 2"
我的意图是在代码的其他地方声明一个返回的函数,以使其可重复使用。
尽管如此,如果我写:
const myLogger = argTwo => console.log(argOne, argTwo);
// Returns reference to a function that doesn't inherit parent's scope
const curry = argOne => myLogger;
const initiateFunction = curry(1); // Seems to be ok
initiateFunction(2); // ReferenceError: argOne is not defined
有什么问题以及如何解决?
答案 0 :(得分:0)
我感到困惑的是,在那个时候,currying对我来说是一个非常新的概念。结合箭头功能,它看起来很棒,但也很难掌握。
如果我们使用经典的函数定义来重新编写示例,则很容易理解为什么第二种方法不起作用。
const curry = argOne => argTwo => console.log(argOne, argTwo);
curry(1)(2) // -> 1 2
// Is equivalent to
function curry (argOne) {
return function(argTwo) {
console.log(argOne, argTwo)
}
}
在第二个示例中,myLogger
无法访问argOne
,如注释中正确说明的那样:
const myLogger = argTwo => console.log(argOne, argTwo);
const curry = argOne => myLogger;
curry(1)(2) // -> Error
// Is equivalent to
function myLogger(argTwo) {
console.log(argOne, argTwo)
}
function curry(argOne) {
return myLogger // which has no idea what is argOne since declared outside of curry scope
}