Search code examples
angulartypescriptthiseval

Angular/Typescript Eval and this


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);
    }
  };

}

Solution

  • PS: The eval function is very dangerous and should be used with precaution !!!

    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: Generally, you don't need to use the eval function, you can explain even without giving the whole code behind your desired behavior and people can help you figure out how to make it work.

    EDIT: 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.