1

Closed

Fields are undefined in some cases.

description

class Animal {
    constructor(public name: string) { alert(this.getInfo()); }
    getInfo() {
        return "Name: " + this.name;
    }
}

class Snake extends Animal {
    constructor(name: string) { super(name); }
    public color:string = "red";
    
    getInfo() {
        return "Color: " + this.color + "; " + super.getInfo());
    }
}

var snake = new Snake("Snake1");
it returns that color is undefined
Closed Mar 6, 2013 at 5:06 PM by paulb
Yes, as you can see in the generated jscript code, the call to super is done before the initialization.

You can resolve this by assigning to the color field, before the call to super. like this.
// inside class Snake
    public color: string;
    constructor(name: string) {
        this.color = 'red';
        super(name);
    }

comments

rb126 wrote Mar 6, 2013 at 9:01 AM

I wonder if this is an order of initialisation thing? color is effectively initialised in the ctor but if super(name) is called before color is initialised, since both occur in the ctor, maybe that is causing the problem? I wonder if attributes declared with an initialisation value should be specified to be initialised before the body of the ctor runs?