角度/打字稿评估和这个 [英] Angular/Typescript Eval and this

查看:66
本文介绍了角度/打字稿评估和这个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在理解eval如何在打字稿/角度中使用它时遇到了问题.有人可以帮我评估一下在这里工作吗?这只是一个演示程序,因此请忽略逻辑没有道理的事实.我只想让eval用动态值更新动态数组.

So I am having a problem understanding how eval works with this in typescript/angular. Could someone please help me get the eval to work here? This is just a demo program so just ignore the fact that the logic doesn't make sense. I would just like to have eval update a dynamic array with a dynamic value.

https://stackblitz.com/edit/angular-pfyt7q?file = src%2Fapp%2Fapp.component.ts

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

  constructor() {
    this.TestClass.Run("this.arrTest1 = [1];");
    this.TestClass.Run("this.arrTest2 = [2];");
    this.TestClass.Run("this.arrTest3 = [3];");
    console.log(this.arrTest1);   //Logs: [] (I want: [1])
    console.log(this.arrTest2);   //Logs: [] (I want: [2])
    console.log(this.arrTest3);   //Logs: [] (I want: [3])
  };

  TestClass = {
    Run : (pString) => {
      (0, eval)(pString);
      eval(pString);
    }
  };

}

推荐答案

PS:eval函数非常危险,应谨慎使用!!!

但是,由于我很友好,我将向您展示如何使代码正常工作:为了指定eval函数的上下文,可以使用如下所示的调用javascript函数:

But, because I'm kind, I will show you how to make your code work: In order to specify the context of your eval function you can use the call javascript function like this:

this.TestClass.Run.call(this, "this.arrTest2 = [2];");

PS2:通常,您不需要使用eval函数,甚至可以在不需要给出所需行为的完整代码的情况下进行解释,并且人们可以帮助您弄清楚如何使其发挥作用.

如果您想要的行为是具有动态数组/值,则可以使用一个简单的对象并将其属性动态添加到该对象.假设您的对象是A:您可以使用A [varName]动态创建对象属性.

If your desired behavior is to have dynamic arrays/values, you can use a simple object and add your attribute to it dynamically. Let say your object is A: You can use A[varName] to create an object attribute dynamically.

这篇关于角度/打字稿评估和这个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆