我有一个这样的课程:
export class HelloComponent {
recipient = 'World';
constructor() {
this.sayHello();
}
sayHello() {
const msg = `Hello ${this.recipient}`;
console.log(msg);
}
}
从构造函数调用时,sayHello
正常工作。
但是,当方法window.requestAnimationFrame
被调用时,它会抛出:
// Uncaught TypeError: Cannot read property 'recipient' of null
怎么了?
答案 0 :(得分:0)
在类外调用类方法时,this
引用不再引用该类。该方法需要更改为属性:
sayHello = () => {
const msg = `Hello ${this.recipient}`;
console.log(msg);
}
答案 1 :(得分:0)
如果您当前有这样的事情:
const hc = new HelloComponent();
window.requestAnimationFrame(hc.sayHello);
将第二行更改为:
window.requestAnimationFrame(hc.sayHello.bind(hc));
或:
window.requestAnimationFrame(() => hc.sayHello());
两种语法都将确保回调仍然将this
绑定到hc
。关于基于bind
的解决方案,另请参见this MDN article ("Creating a bound function")中的说明。