arrow函数能在课堂上被提升吗?(javascript)



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();
};

不悬挂箭头功能,只悬挂常规功能。为什么,在animate函数内部,可以调用this.test?类中箭头函数的不同行为?

虽然箭头函数没有被提升,但这里的箭头函数并不是,而是箭头函数-这里使用的是类字段,它们是为构造函数内的实例赋值的语法糖(在构造函数的开头,在任何super调用之后(。您的代码相当于:

class App {
constructor() {
this.animate = () => {
this.test(); // ---> here!
};
this.test = () => {
console.log('here!');
};
this.canvas = document.createElement('canvas');
// ...
}
}

这不是吊装的问题。

首先,this.animate得到一个分配给它的函数。然后,this.test得到一个指定给它的功能。然后,最终,在requestAnimationFrame之后,调用this.animate

对于一个更简单的例子:

const fn1 = () => {
fn2();
};
const fn2 = () => {
console.log('fn2');
};
fn1();

只要将函数分配给变量的行在函数被调用之前已经运行,一切都应该正常。

最新更新