Accessing member of base class

typescript

Solution

Working example. Notes below.

class Animal {
    constructor(public name) {
    }

    move(meters) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    move() {
        alert(this.name + " is Slithering...");
        super.move(5);
    }
}

class Horse extends Animal {
    move() {
        alert(this.name + " is Galloping...");
        super.move(45);
    }
}

var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");

sam.move();
tom.move(34);

You don't need to manually assign the name to a public variable. Using `public name` in the constructor definition does this for you.

You don't need to call `super(name)` from the specialised classes.

Using `this.name` works.

Notes on use of `super`.

This is covered in more detail in section 4.9.2 of the language specification.

The behaviour of the classes inheriting from `Animal` is not dissimilar to the behaviour in other languages. You need to specify the `super` keyword in order to avoid confusion between a specialised function and the base class function. For example, if you called `move()` or `this.move()` you would be dealing with the specialised `Snake` or `Horse` function, so using `super.move()` explicitly calls the base class function.

There is no confusion of properties, as they are the properties of the instance. There is no difference between `super.name` and `this.name` - there is simply `this.name`. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.

Problem

See the inheritance example from the playground on the TypeScript site: ``` class Animal { public name; constructor(name) { this.name = name; } move(meters) { alert(this.name + " moved " + meters + "m."); } } class Snake extends Animal { constructor(name) { super(name); } move() { alert("Slithering..."); super.move(5); } } class Horse extends Animal { constructor(name) { super(name); } move() { alert(super.name + " is Galloping..."); super.move(45); } } var sam = new Snake("Sammy the Python"); var tom: Animal = new Horse("Tommy the Palomino"); sam.move(); tom.move(34); ``` I have changed one line of code: the alert in `Horse.move()`. There I want to access `super.name`, but that returns just `undefined`. IntelliSense is suggesting that I can use it and TypeScript compiles fine, but it does not work. Any ideas?

Original source