How to use requestAnimationFrame with a TypeScript object?

The best approach I've found.

requestAnimationFrame(this.Render.bind(this));

.bind(this) creates a new function that has its this keyword set to the provided value.

Bonus Reading

  • MDN: bind function

On Firefox 49.0.1 I've got an error message using Ryan Cavanaugh solution.

SyntaxError: bad method definition

for the line :

Render = ()=> {

The work around I've found looks like this :

class Test{

    constructor(){

        this.Render = ()=> {
            requestAnimationFrame( this.Render );
        };

    }
}

You've lost this context. Two possible fixes:

class Contoso
{
   /* ... */

   // Use () => syntax so Render always gets 'this' context
   // from the class instance
   Render = () => {
      //...snip doing any actual drawing for the purpose of this question
      requestAnimationFrame(this.Render);
   }
}

The alternate fix is probably slightly clearer, but has the downside of making a lot more allocations (you probably don't want to allocate 1 closure per frame!)

   Render() {
      //...snip doing any actual drawing for the purpose of this question
      requestAnimationFrame(() => this.Render);
   }

Use arrow syntax (lambda):

requestAnimationFrame(() => this.Render());