如果在其他地方声明了返回的函数,则无法进行咖喱

时间:2019-08-06 11:39:05

标签: javascript closures currying

以下代码运行良好:

// 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

有什么问题以及如何解决?

1 个答案:

答案 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
}