I would like to roll a JavaScript class for doing animations via window.requestAnimationFrame
. Unfortunately, when I run my code, the Google Chrome Developer Tools throws this at me:
script.js:10 Uncaught TypeError: Cannot read properties of undefined (reading '#counter')
at #loop (script.js:10:47)
Superficially, it seems like that after the first iteration the reference this
is lost. How could I circumvent that issue?
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);
}
}
1