如何不使用eval调用字符串中的箭头函数?尝试new Function未果
eval Hey there! I’ve run into this exact issue before—using eval works for running arrow functions stored as strings, but it’s not ideal for security and scope reasons. Let’s break down why your new Function attempt might have failed, and fix it with a reliable solution.
First, let’s recap the working eval approach so we’re on the same page:
// Your original working eval code const arrowFuncStr = "x => x * 2"; const funcFromEval = eval(arrowFuncStr); console.log(funcFromEval(5)); // Outputs 10
Why new Function Might Have Failed
The most common mistake here is trying to pass the arrow function string directly as the new Function body. For example, this will throw an error:
// ❌ This won't work! const badFunc = new Function(arrowFuncStr); // Uncaught SyntaxError: Unexpected token '=>'
That’s because new Function expects the last argument to be a function body (statements), not an expression like an arrow function. Arrow functions are expressions, not standalone statements, so we need to wrap them in a return statement to make them valid in the function body.
The Correct new Function Approach
We can fix this by creating a wrapper function that returns the arrow function expression, then immediately invoking that wrapper to get our desired function. Here’s how:
// ✅ Working new Function solution const arrowFuncStr = "x => x * 2"; const funcFromNewFunc = new Function(`return ${arrowFuncStr}`)(); console.log(funcFromNewFunc(5)); // Outputs 10
Let’s break this down:
new Function(return ${arrowFuncStr})creates an anonymous function whose body isreturn x => x * 2.- Adding
()at the end immediately calls this anonymous function, which returns the arrow function we want.
Handling Complex Arrow Functions
This method works for any arrow function syntax, including multi-parameter functions or ones with block bodies:
// Multi-parameter arrow function const multiParamStr = "(a, b) => a + b * 2"; const multiParamFunc = new Function(`return ${multiParamStr}`)(); console.log(multiParamFunc(3, 4)); // Outputs 11 // Arrow function with block body const blockBodyStr = "x => { const doubled = x * 2; return doubled + 1; }"; const blockBodyFunc = new Function(`return ${blockBodyStr}`)(); console.log(blockBodyFunc(5)); // Outputs 11
A Note on Security & Scope
While new Function is safer than eval (it runs in the global scope instead of your local scope), you still need to be cautious if the string comes from untrusted input. Both methods carry injection risks, so only use this with strings you control or fully sanitize.
内容的提问来源于stack exchange,提问作者user9494009

