Javascript 向方法传递引用时,此上下文丢失
在这个例子中Javascript 向方法传递引用时,此上下文丢失,javascript,typescript,ecmascript-6,Javascript,Typescript,Ecmascript 6,在这个例子中 class Car { describe() { console.log("I have " + this.wheels); } testMe() { setTimeout( this.describe, 1000); } constructor(wheels) { this.wheels = wheels; } } let myCar = new Car(4); myCar.te
class Car {
describe() {
console.log("I have " + this.wheels);
}
testMe() {
setTimeout( this.describe, 1000);
}
constructor(wheels) {
this.wheels = wheels;
}
}
let myCar = new Car(4);
myCar.testMe(); // I have undefined
为什么this
的预期值没有在descripe
函数中传递
编辑:您能确认is setTimeout是一个箭头函数吗?我不会得到未定义的
?裸函数引用没有上下文,即使它是作为对象的属性检索的
在testMe
函数中,您需要:
setTimeout(() => this.describe(), 1000);
或
或
当然,最后一个可以编写为箭头函数,但是如果您这样做的话,您还可以使用第一个版本,而不需要this
的本地副本
关于您的编辑,可以只传递这个。通过使descripe
成为一个箭头函数,从构造函数内部分配,但请注意,这意味着对象的每个实例都有自己的函数副本,而不是类的prototype
上只有一个副本:
constructor(wheels) {
this.wheels = wheels;
this.describe = () => {
console.log("I have " + this.wheels);
}
}
顺便说一句,我写了一个关于类似问题的答案。为什么要添加typescript
标记?因为如果没有绑定、调用或应用,它相当于编写setTimeout(function(){console.log(“我有”+this.wheels);},1000)@Lev你的观点是什么?您在该注释中编写的代码也不起作用。
let self = this;
setTimeout(function() {
self.describe();
}, 1000);
constructor(wheels) {
this.wheels = wheels;
this.describe = () => {
console.log("I have " + this.wheels);
}
}