在 class 中使用 requestAnimationFrame

Use requestAnimationFrame in a class

我无法找到如何在 class 中使用 requestAnimationFrame

此代码运行良好:

window.onload = function () {
    var width = 20;
    function animation() {
        width++;
        var element = document.getElementById("box");
        element.style.width = width + "px";
        requestAnimationFrame(animation);
    }
    requestAnimationFrame(animation);
};

但是当我尝试将其放入 class 时,我没有得到任何结果。

class Animation{
    width: number = 20;

    constructor() {
        requestAnimationFrame(this.loop);
    }
    loop() {
        this.width++;
        var element = document.getElementById("box");
        element.style.width = this.width + "px";
        requestAnimationFrame(this.loop);
    }
}
window.onload = function () {
    var animation = new Animation();
};

谁能告诉我这里出了什么问题?

requestAnimationFrame(this.loop); 如果您要向其他人传递 他们 将要调用的函数,请使用箭头,即 requestAnimationFrame(()=>this.loop());loop = () => {

更多:https://www.youtube.com/watch?v=tvocUcbCupA