打字稿使用此关键字
Typescript use of this keyword
我们正在使用打字稿进行开发。
我还收到一条评论意见,说我们不应该使用 '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
的变量并在每个 class 方法的开头用 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!
});
}
}
在这个例子中,self
被捕获时它持有对 MyClass 实例的引用,并且在回调函数中它仍然指向 MyClass 实例,但在回调函数中 this
可能引用至于别的,就看回调函数怎么调用了。
我们正在使用打字稿进行开发。 我还收到一条评论意见,说我们不应该使用 '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
的变量并在每个 class 方法的开头用 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!
});
}
}
在这个例子中,self
被捕获时它持有对 MyClass 实例的引用,并且在回调函数中它仍然指向 MyClass 实例,但在回调函数中 this
可能引用至于别的,就看回调函数怎么调用了。