Suggested improvement on how you cope with the javascript "this" issue

Topics: Language Specification
Jul 26, 2013 at 10:56 PM
This is quite a simple request but an important one I feel.

Currently TypeScript uses an (imo) messy way to cope with the way "this" changes inside a class when moving from function to function.
Game.prototype.Start = function () {
        var _this = this;
        this.GUI.WriteLine('Hello, This is the matrix...\nWrite something');
        this.GUI.GetInput(function (val) {
            _this.GUI.WriteLine('You wrote: ' + val);
            _this.GUI.WriteLine('Well done :)');
        });
    };
should be
Game.prototype.Start = function () {
        this.GUI.WriteLine('Hello, This is the matrix...\nWrite something');
        this.GUI.GetInput(function (val) {
            this.GUI.WriteLine('You wrote: ' + val);
            this.GUI.WriteLine('Well done :)');
        }.bind(this));
    };
I feel it's a lot cleaner and it is definitely more consistent.
Jul 26, 2013 at 11:03 PM
Your suggestion is much cleaner, but is also ES5 only. ES3 would require an arguably equally messy polyfill.
Jul 26, 2013 at 11:11 PM
Ahh yes I see, tweaking the suggestion slightly then...

As there is an option to target either ES3 or ES5, if you have ES5 enabled use this method, if not, use the current method perhaps.

It's something to consider anyway.
Jul 28, 2013 at 11:46 AM
The bind is also slower: http://jsperf.com/bind-vs-local-this