gpt4 book ai didi

javascript - 箭头函数可以在类里面提升吗? (javascript)

转载 作者:行者123 更新时间:2023-12-05 00:31:33 26 4
gpt4 key购买 nike

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

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

关于javascript - 箭头函数可以在类里面提升吗? (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65511154/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com