有没有办法通过[this]变量设置变量的值?

时间:2017-11-18 21:50:01

标签: typescript this

我在班级获得了一个变量,比如称它为“x”。

在该组件文件中运行this.x='some value';之类的内容是没有问题的,因为它有效。

但是如果你想通过以下函数做到这一点:

setThisValue('x','some value');

嗯,我做了一次糟糕的尝试,知道它不起作用,我在下面发布了。以下显然不起作用。但是什么是补救措施?

setThisValue(key,val){
   this.key = val; // this clearly would not work.
   // short of doing eval, is there a way to make it happen? 
}

1 个答案:

答案 0 :(得分:2)

使用bracket notation

this[key] = val;