如何在JavaScript中动态创建高阶函数?

How to dynamically create higher-order functions in JavaScript?

我正在尝试编写一个 JavaScript 函数来执行以下操作:如果我调用

const multiply = define("x", "y", "x * y");

我希望multiply成为

function(x) {
    return function(y) {
        return x * y;
    }
}

参数数量事先未知。最后一个始终是最终的 return,每个其他参数都是内部函数的参数。我的 define 函数应该是什么?

我知道我可以写 const multiply = x => y => x * y,但我需要代码尽可能对用户友好,而且像这样的高阶函数对于不经常使用它们的人来说并不完全清楚.

我试过使用 Function 构造函数,但我最想得到的是 returns me function(x, y) { return x * y; } 这不是我想要的。

我的想法是逐步构建函数,所以首先我必须创建一个函数 f,需要 y 和 returns x * y,然后我必须创建 g 需要 x 和 returns f(y)。但这就是我被困的地方。

谁能告诉我如何解决这个问题?谢谢。

一般来说,在运行时从文本创建代码并不是一个好主意。但是 如果 您信任要从中创建函数的文本的来源,则可以使用 new Function 从文本创建函数。请注意,就其本质而言,它允许任意代码执行。

在你的情况下,如果最后一个参数始终是最终函数的主体,并且导致它的参数是参数名称,那么循环应该这样做:

function define(...args) {
  // Build the text of the functions
  let text = "";
  for (let n = 0; n < args.length; ++n) {
    if (n == args.length - 1) {
      text = text + "(" + args[n] + ")";
    } else {
      text = text + "(" + args[n] + ") => ";
    }
  }
  console.log(text);
  // Create them by creating a wrapper function and executing it.
  // If we wanted to complicate the logic above,
  // we could just use this to create the top-
  // level function and not execute it, but this
  // is simpler.
  return new Function("return " + text + ";")();
}
const multiply = define("x", "y", "x * y");
console.log("multiply(3)(5) => ", multiply(3)(5));
const multiply2 = define("x", "y", "z", "x * y * z");
console.log("multiply2(3)(5)(2) => ", multiply2(3)(5)(2));
.as-console-wrapper {
  max-height: 100% !important;
}