Wednesday, September 20, 2017

Beware of THIS in Javascript

Coming to Javascript from other object oriented languages can be frustrating due to its alien syntax structure.  I was told and have read that a common hang up is with the this construct behavior in Javascript.  So, naturally, I fell for it right off the bat.

I was staring at the following code and everything looked fine:


    update () {
        
        this._renderer.render(this._world);

        requestAnimationFrame(this.update);
    }

But alas when run I was encountering the dreaded "Uncaught TypeError: Cannot read property '_renderer' of undefined." This is because this in Javascript does not retain its original context when called from a callback.

The most concise description of the problem I could find came from TypeScript's github here: https://github.com/Microsoft/TypeScript/wiki/'this'-in-TypeScript

This is where some of the new ES6 syntax comes in handy. This still feels alien and unnatural to me coming from AS3/C# as it should "just work right?"

So I chose to use the fat arrow approach to the problem so that update could be called as a callback and landed on this as a solution:



    public update = () => {
        
        this._renderer.render(this._world);

        requestAnimationFrame(this.update);
    }

No comments:

Post a Comment