我们正在使用打字稿进行开发。我也收到一条评论评论,认为我们不应使用“ this”关键字,它会影响性能。本地代码:
export Class MyClass
{
public myMethod1(Data) {
this.myMethod2();
}
public myMethod2() {
}
}
我们正在像下面那样使用来访问'this'。更改后:
export Class MyClass
{
public myMethod1(Data) {
let self = this;
self.myMethod2();
}
public myMethod2() {
}
}
因此,请您帮助使用'this'关键字。
这对性能没有影响。但是,使用一个名为self
的变量并在每个类方法的开头使用this
对其进行初始化,可能有助于避免不必要的行为。例如:
Class MyClass
{
public foo () {
const self = this;
callMeLater(function (){
console.log(self); // "self" is always the instance of MyClass
console.log(this); // "this" may refer to another object!
});
}
}