Last active
August 28, 2020 07:26
-
-
Save watab0shi/74f7fdb22b2cfbae72d57dd7fa2718b5 to your computer and use it in GitHub Desktop.
requestAnimationFrame with Function.prototype.bind()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Document</title> | |
| </head> | |
| <body> | |
| <p>Time: <span id="txt-time">0</span></p> | |
| <script> | |
| class Animator { | |
| constructor({ element }) { | |
| Object.assign(this, { | |
| element, | |
| /** | |
| * ↓ Function.prototype.bind() で関数が呼び出されたときの this の値をこのクラスに固定した関数のコピーを返す | |
| * ref: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Function/bind | |
| */ | |
| boundUpdate: this.update.bind(this) | |
| }); | |
| requestAnimationFrame(this.boundUpdate); | |
| } | |
| update(timestamp) { | |
| this.element.textContent = timestamp; | |
| /** | |
| * ↓ このクラスをthisで参照するためだけに Arrow Function で括っている | |
| * 引数の記述も書かないといけなくて面倒 | |
| */ | |
| // requestAnimationFrame(t => { this.update(t); }); | |
| /** | |
| * this.boundUpdate が呼び出される時の関数内の this がこのクラスに固定されている | |
| */ | |
| requestAnimationFrame(this.boundUpdate); | |
| // requestAnimationFrame(this.update.bind(this));// これでもいけるけど毎回bindする必要ないので変数にいれとくのがよさそ。 | |
| } | |
| } | |
| document.addEventListener('DOMContentLoaded', () => { | |
| new Animator({ element: document.getElementById('txt-time') }); | |
| }); | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment