fac*_*cVV 6 javascript hoisting
class App {
constructor() {
this.canvas = document.createElement('canvas');
document.body.appendChild(this.canvas);
this.ctx = this.canvas.getContext('2d');
this.pixelRatio = window.devicePixelRatio > 1 ? 2 : 1;
window.addEventListener('resize', this.resize.bind(this), false);
this.resize();
window.requestAnimationFrame(this.animate);
}
resize() {
this.stageWidth = document.body.clientWidth;
this.stageHeight = document.body.clientHeight;
}
animate = () => {
this.test(); // ---> here!
};
test = () => {
console.log('here!');
};
}
window.onload = () => {
new App();
};Run Code Online (Sandbox Code Playgroud)
箭头函数不会被提升,只有常规函数会被提升。为什么animate函数内部可以调用this.test?类中箭头函数的不同行为?
虽然箭头函数没有被提升,但这里不仅仅是箭头函数 - 您在这里使用类字段,它们是用于为构造函数内的实例分配值的语法糖(在构造函数的开头,只需任何super通话后)。您的代码相当于:
class App {
constructor() {
this.animate = () => {
this.test(); // ---> here!
};
this.test = () => {
console.log('here!');
};
this.canvas = document.createElement('canvas');
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
这不是吊装的问题。
首先this.animate获取分配给它的函数。然后this.test获取分配给它的函数。requestAnimationFrame然后,最终在,之后this.animate被调用。
一个更简单的例子:
class App {
constructor() {
this.animate = () => {
this.test(); // ---> here!
};
this.test = () => {
console.log('here!');
};
this.canvas = document.createElement('canvas');
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
只要将函数分配给变量的行在函数被调用之前运行,一切都应该正常。