Thursday, July 24, 2014

On TypeScript, the this keyword doesn't always reference the instance of a class

///<reference path='jquery.d.ts' />

class Mate {
    public n : number;

    public name : string = "Freddie";

    public nick : string = "Fred";



    public message() : void {

        var people = new Array<Person>();



        {
            var p = new Person();
            p.name = "Ely";
            people.push(p);
        }

        {
            var p = new Person();
            p.name = "Raymund";
            people.push(p);
        }




        $.each(people, function() {
            alert('inline: ' + this.name + ' -- ' + this.nick);
        });
        /*
        Outputs:
        inline: Ely -- undefined
        inline: Raymund -- undefined
        */


        $.each(people, this.alerter);
        /*
        Coming from traditional OOP, I expected:
        Freddie -- Fred
        Freddie -- Fred

        What happens:
        Ely -- undefined
        Raymund -- undefined
        */



        $.each(people, () => alert('inline: ' + this.name + ' -- ' + this.nick) );
        /*
        Outputs:
        inline: Freddie -- Fred
        inline: Freddie -- Fred
        */


        $.each(people, () => this.alerter());
        /*
        Outputs:
        Freddie -- Fred
        Freddie -- Fred
        */


    }

    public alerter() : void {
        alert(this.name + ' -- ' + this.nick);

    }

}

class Person {
    public name : string;
}


$(function() {
    var m = new Mate();
    m.message();
});