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

Angular/TypeScript中eval与this绑定异常求助:如何用eval更新数组

我明白你遇到的问题了——想用eval动态给Angular组件里的数组赋值,但现在this的指向不对,导致数组始终是空的。咱们来一步步解决这个问题。

问题根源分析

你的TestClass.Run用了箭头函数,虽然箭头函数会继承外层的this(也就是AppComponent实例),但这里的核心问题出在eval的执行上下文上:

  • (0, eval)(pString)是间接调用eval,这种情况下eval的执行上下文是全局对象(浏览器里的window),所以代码里的this指向的是全局,不是你的组件实例。
  • 直接调用eval(pString)时,因为Angular/TypeScript默认开启严格模式,箭头函数里的this虽然指向组件实例,但严格模式下eval内部的this不会自动绑定到当前上下文,导致赋值还是没生效到组件的数组上。

解决方案

这里给你几种可行的修改方式,都能让eval正确操作组件实例的数组:

方案一:传递组件实例,替换代码中的this

把组件实例作为参数传给Run方法,然后将代码里的this替换为实例变量,直接操作实例属性:

export class AppComponent {
  arrTest1 = [];
  arrTest2 = [];
  arrTest3 = [];

  constructor() {
    this.TestClass.Run(this, "this.arrTest1 = [1];");
    this.TestClass.Run(this, "this.arrTest2 = [2];");
    this.TestClass.Run(this, "this.arrTest3 = [3];");

    console.log(this.arrTest1); // 现在输出: [1]
    console.log(this.arrTest2); // 现在输出: [2]
    console.log(this.arrTest3); // 现在输出: [3]
  };

  TestClass = {
    Run: (componentInstance, pString) => {
      // 把代码中的this.替换为组件实例的引用
      const targetCode = pString.replace(/this\./g, 'componentInstance.');
      eval(targetCode);
    }
  };
}

方案二:用Function构造函数替代eval,明确指定this

Function构造函数可以创建动态函数,再通过call方法明确绑定执行时的this,比eval更可控:

export class AppComponent {
  arrTest1 = [];
  arrTest2 = [];
  arrTest3 = [];

  constructor() {
    this.TestClass.Run(this, "this.arrTest1 = [1];");
    this.TestClass.Run(this, "this.arrTest2 = [2];");
    this.TestClass.Run(this, "this.arrTest3 = [3];");

    console.log(this.arrTest1); // 现在输出: [1]
    console.log(this.arrTest2); // 现在输出: [2]
    console.log(this.arrTest3); // 现在输出: [3]
  };

  TestClass = {
    Run: (componentInstance, pString) => {
      // 创建动态函数并绑定组件实例为this
      new Function(pString).call(componentInstance);
    }
  };
}

方案三:用普通函数+call绑定this

如果一定要用eval,可以把Run改成普通函数,调用时用call绑定组件实例作为this:

export class AppComponent {
  arrTest1 = [];
  arrTest2 = [];
  arrTest3 = [];

  constructor() {
    // 调用Run时用call绑定组件实例
    this.TestClass.Run.call(this, "this.arrTest1 = [1];");
    this.TestClass.Run.call(this, "this.arrTest2 = [2];");
    this.TestClass.Run.call(this, "this.arrTest3 = [3];");

    console.log(this.arrTest1); // 现在输出: [1]
    console.log(this.arrTest2); // 现在输出: [2]
    console.log(this.arrTest3); // 现在输出: [3]
  };

  TestClass = {
    // 用普通函数,让call绑定的this生效
    Run: function(pString) {
      eval(pString);
    }
  };
}

额外提醒

虽然你说这只是演示,但还是要注意:eval和Function构造函数都存在安全风险(如果执行的代码来自不可信来源),而且在TypeScript中这类动态执行代码的方式会失去类型检查的优势,实际项目中尽量避免使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:19:48