You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用eval调用字符串中的箭头函数?尝试new Function未果

How to Execute Arrow Functions Stored in Strings Without 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:

  1. new Function(return ${arrowFuncStr}) creates an anonymous function whose body is return x => x * 2.
  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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:03:44