从打字稿手册中阅读示例:
class Animal {
name:string;
constructor(theName: string) { this.name = theName; }
move(meters: number = 0) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
constructor(name: string) { super(name); }
move(meters = 5) {
alert("Slithering...");
super.move(meters);
}
}
class Horse extends Animal {
constructor(name: string) { super(name); }
move(meters = 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);
问题是关于这条线var tom: Animal = new Horse("Tommy the Palomino");
:
据我了解
tom
是 aAnimal
具有 a 的属性Horse
。是对的吗?这样做有什么意义?不声明为
var tom: Horse = ...
?只有一个版本让他有机会降级/更改/进化到一个
Snake
或任何其他Animal
. 我对吗?...或者也许这只是一个错字?