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

Angular中使用new Function调用嵌套函数报错求助

解决new Function中无法访问嵌套函数的问题

你遇到的问题是因为testFunc执行后默认返回undefined,所以调用testFunc().nestFunc2()时找不到嵌套函数。要让脚本能访问到嵌套函数,需要让testFunc返回一个包含这些嵌套函数的对象,同时保留原有的逻辑。

修改后的代码如下:

test() {
    const script = `
    var value = 1 +4;
    console.log('value',value);
    testFunc('Success');
    testFunc().nestFunc2();
    console.log("End Script");
  `;

    var testFunc = (msg?: string) => {
      // 保留原有的日志逻辑
      if (msg !== undefined) {
        console.log('Test Function', msg);
      }
      // 返回包含嵌套函数的对象
      return {
        nestFunc1: () => {
          alert('hi');
        },
        nestFunc2: () => {
          alert('hi');
        }
      };
    };

    const userFunction = new Function('testFunc', script);
    userFunction(testFunc);
}

这样修改后,testFunc()会返回包含nestFunc1和nestFunc2的对象,脚本里就能正常调用testFunc().nestFunc2()了。同时testFunc('Success')也能正常执行日志输出。

内容的提问来源于stack exchange,提问作者Ka Tech

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 12:50:21