📜  如何在 javascript 代码示例中创建动态函数

📅  最后修改于: 2022-03-11 15:01:27.906000             🧑  作者: Mango

代码示例1
// for async
const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
// assume someAsyncCall is a call to another async func we await for that returns 1 (just make this simpler)
const func = new AsyncFunction('arg1', 'arg2', 'return arg1 * arg2 * await someAsyncCall();');
// now use the function, assuming we are in an async function for the following to work
await func(2,2); // => 4


// for normal non-async functions it's simpler just use the Function constructor
const func = new Function('arg1', 'arg2', 'return arg1 * arg2;');
// now use the function
func(2,2); // => 4