如果返回的函数在别处声明,则柯里化不起作用
Currying doesn't work if returned function declared elsewhere
以下代码运行良好:
// 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
有什么问题以及如何解决?
我很困惑,因为那时柯里化对我来说是一个非常新的概念。结合箭头函数,看起来很棒,但也更难掌握。
如果我们使用经典的函数定义重写这个例子,就很容易理解为什么第二种方式不起作用。
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
}
以下代码运行良好:
// 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
有什么问题以及如何解决?
我很困惑,因为那时柯里化对我来说是一个非常新的概念。结合箭头函数,看起来很棒,但也更难掌握。
如果我们使用经典的函数定义重写这个例子,就很容易理解为什么第二种方式不起作用。
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
}