簡體   English   中英

如何在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;
    }
}

參數數量事先未知。 最后一個總是最終的返回值,其他每個參數都是內部函數的參數。 我的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM