Tommy the Palomino moves 45 meters and not 34 as I thought.

Topics: General
May 28, 2014 at 8:56 PM
class Animal {
name: string;
constructor(theName: string) { this.name = theName; }
move(meters: number) {
    alert(this.name + " moved " + meters + "m.");
}
}

class Snake extends Animal {
constructor(name: string) { super(name); }
move() {
    alert("Slithering...");
    super.move(5);
}
}

class Horse extends Animal {
constructor(name: string) { super(name); }
move() {
    alert("Galloping...");
    super.move(45);
}
}

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

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

Tom does not move 34 meters. Tom moves 45 meters. Is that supposed to happen? I thought that Tom would have moved the 34 meters as specified.
May 28, 2014 at 9:13 PM
Edited May 28, 2014 at 9:14 PM
You don't understand JavaScript inheritance. The methods on sub (child) classes completely replace methods of the same name on super (parent) classes. This is because JavaScript will find the first method name that matches in the prototype chain.

To fix this, you need to access the method on the lower type directly...
Animal.prototype.move.call(tom, 24);
May 28, 2014 at 9:26 PM
Just to add: TypeScript is a "typing" layer over JavaScript (for the most part). I would suggest learning how JavaScript works first (especially prototypes) to properly understand various behaviors from resulting JS code compiled from TS. This tends to be an issue with C# type developers thinking C# instead of JS. ;) Anyhow, try this:
class Animal {
    name: string;
    constructor(theName: string) { this.name = theName; }
    move(meters: number) {
        alert(this.name + " moved " + meters + "m.");
    }
} 

class Snake extends Animal {
    constructor(name: string) { super(name); }
    move(meters: number = 5) {
        alert("Slithering...");
        super.move(meters);
    }
} 

class Horse extends Animal {
    constructor(name: string) { super(name); }
    move(meters: number = 45) {
        alert("Galloping...");
        super.move(meters);
    }
}

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

 sam.move(); 
 tom.move(34); 
// ... or use your existing code and run ...
Animal.prototype.move.call(tom, 34);
May 28, 2014 at 9:32 PM
Edited May 28, 2014 at 9:32 PM
So..., why not explain that one tricky part in the example? And no, I guess I don't understand JavaScript prototypes. I have been using JavaScript for a long time, but always stayed away from prototypes because of the confusion.
May 28, 2014 at 9:51 PM
My apologies - I guess after reading the post it may come across as sarcastic, lol. I was being sincere - taking time to understand prototype inheritance will greatly help understand classes in TS. ;)