Using requestAnimationFrame() in recursion, "this" problem

Hello,
could someone help me with requestAnimationFrame, how can I deal with “this” in recursion function?

ModelLoader.prototype.animate = function () {
         console.log('animate, this: ' + this);
         requestAnimationFrame( this.animate );
         this.controls.update();
         this.stats.update();
 };

This console.log() first time returns:

animate, this: [object Object]

and of course next time:

animate, this: [object Window]

I would like to use prototyping. To have my code inside own “classes”.
I was sure it will be quite easy, I was wrong :slight_smile:

Thanks,
Simon

One way to solve the problem:

function animate(){

    requestAnimationFrame( this.animate );
    this.controls.update();
    this.stats.update();

}

And in your constructor:

function ModelLoader() {

    this.animate = animate.bind( this );

}
2 Likes