将 requestAnimationFrame 循环封装在类中会丢失对象的 this 引用

问题描述 投票:0回答:1

我想推出一个 JavaScript 类来通过

window.requestAnimationFrame
制作动画。不幸的是,当我运行我的代码时,Google Chrome 开发者工具向我抛出了这个:

script.js:10 Uncaught TypeError: Cannot read properties of undefined (reading '#counter')
    at #loop (script.js:10:47)

从表面上看,第一次迭代后,参考

this
似乎丢失了。我怎样才能避免这个问题?

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>WebTest</title>
    </head>
    <body>
        <script src="script.js"></script>
        
        <script>
            const alerter = new Alerter();
            alerter.start();
        </script>
    </body>
</html>

script.js

class Alerter {
    
    #counter = 0;
    
    start() {
        this.#loop();
    }
    
    #loop() {
        const yes = confirm("Counter " + this.#counter + ". Continue?");
        
        if (!yes) {
            return;
        }
        
        this.#counter++;
        
        window.requestAnimationFrame(this.#loop);
    }
}
javascript requestanimationframe
1个回答
0
投票

正如评论所说,您可以通过将回调包装在箭头函数中来修复它。

class Alerter {
    
    #counter = 0;
    
    start() {
        this.#loop();
    }
    
    #loop() {
        console.log("Counter " + this.#counter);
        this.#counter++;
        window.requestAnimationFrame((ms) => this.#loop(ms));
    }
}

let a = new Alerter()
a.start()
© www.soinside.com 2019 - 2024. All rights reserved.