我正在尝试执行如下操作:
class A {
functionA() {
setTimeout(function() {
console.log(this);
}, 1000)
}
}
const a = new A();
a.functionA();
但是this
始终引用窗口对象。我知道您可以设置类似var a = this
的东西,但是还有一种更优雅的方法将其从对象传递到内部函数吗?
您可以使用箭头功能代替常规功能来保持this
上下文:
class A {
functionA() {
setTimeout(() => {
console.log(this);
}, 1000)
}
}
const a = new A();
a.functionA();
另一种方法是.bind(this)
,它将创建一个有界的this
上下文的函数:
class A {
functionA() {
setTimeout((function() {
console.log(this);
}).bind(this), 1000)
}
}
const a = new A();
a.functionA();
除了塞巴斯蒂安的答案,另一个解决方案可以是
class A {
functionA() {
const that = this
setTimeout(function() {
console.log(that);
}, 1000)
}
}
a = new A();
a.functionA();
为了满足OP对[一种更优雅的方式]的期望,在考虑任何其他方法之前,我建议正确使用setTimeout
...
setTimeout
class A { constructor() { this.delay = 3000; } functionA() { setTimeout(console.log, this.delay, this); } } const a = new A(); a.functionA();