See the inheritance example from the playground on the TypeScript site:
class Animal {
public name;
constructor(name) {
this.name = name;
}
move(mete
You are incorrectly using the super
and this
keyword. Here is an example of how they work:
class Animal {
public name: string;
constructor(name: string) {
this.name = name;
}
move(meters: number) {
console.log(this.name + " moved " + meters + "m.");
}
}
class Horse extends Animal {
move() {
console.log(super.name + " is Galloping...");
console.log(this.name + " is Galloping...");
super.move(45);
}
}
var tom: Animal = new Horse("Tommy the Palomino");
Animal.prototype.name = 'horseee';
tom.move(34);
// Outputs:
// horseee is Galloping...
// Tommy the Palomino is Galloping...
// Tommy the Palomino moved 45m.
Explanation:
super.name
, this refers to the prototype chain of the object tom
, not the object tom
self. Because we have added a name property on the Animal.prototype
, horseee will be outputted.this.name
, the this
keyword refers to the the tom object itself. move
method of the Animal base class. This method is called from Horse class move method with the syntax super.move(45);
. Using the super
keyword in this context will look for a move
method on the prototype chain which is found on the Animal prototype.Remember TS still uses prototypes under the hood and the class
and extends
keywords are just syntactic sugar over prototypical inheritance.