[英]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;
}
}
参数数量事先未知。 最后一个总是最终的返回值,其他每个参数都是内部函数的参数。 我的define
函数应该是什么?
我知道我可以编写const multiply = x => y => x * y
,但是我需要代码尽可能地方便用户使用,对于不使用此功能的人来说,像这样的高阶函数并不完全清楚他们经常。
我已经尝试过使用Function
构造函数,但是我设法拿出的大多数Function
都返回了function(x, y) { return x * y; }
function(x, y) { return x * y; }
这不是我想要的。
我的想法是逐步构建函数,因此首先我必须创建一个接受y
并返回x * y
的函数f
,然后我必须创建接受x
并返回f(y)
g
。 但这就是我被困住的地方。
谁能给我一个有关如何解决这个问题的线索? 谢谢。
通常,在运行时从文本创建代码不是一个好主意。 但是, 如果您信任要从中创建函数的文本源,则可以使用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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.