【发布时间】:2018-03-09 15:03:37
【问题描述】:
我是 TypeScript 的初学者。我认为 typescript 可以解决我在 JavaScript 中使用这个范围的所有问题,但似乎并非如此。 请看下面的示例代码:
class Car{
private name : string;
private velocity: number;
constructor ( name:string){
this.name = name;
this.velocity = 0;
}
private speedUp (incrementer: number){
this.velocity += incrementer;
}
public pressAccelerator (power: number){
console.log(this); //here this is a Car object
setTimeout(
function(){
// here is a Timeout object - WTF!!!
// was't this typeScript?
// what's up whit my "this" object scope?
console.log(this);
this.speedUp(power*1.34); //TypeError: this.speedUp is not a function
},
1000
);
}
public getVelocity():number{
return this.velocity;
}
}
let myCar = new Car("Mercedes");
myCar.pressAccelerator(2);
console.log(myCar.getVelocity());
为什么this.speedUp方法中的this没有指向汽车对象?
哪种方法比较实用?
【问题讨论】:
-
this在您的匿名函数中指的是函数本身。正如在一些答案中所说,使用箭头函数具有与您想要的匹配的不同行为。
标签: typescript scope this