【发布时间】:2019-04-16 22:36:43
【问题描述】:
我希望它调用 Animal 类方法,而不是 Snake。
当我进行强制转换时实际发生了什么? typescript <Class>object
class Animal {
name: string;
constructor(theName: string) {
this.name = theName;
this.toString();
console.log(`\tis Animal?: ${this instanceof Animal}`);
console.log(`\tis Snake?: ${this instanceof Snake}`);
console.log(`\tis Horse?: ${this instanceof Horse}`);
console.log()
}
toString() {
console.log(`My name is ${this.name} and I'm a animal`);
}
}
class Snake extends Animal {
name: string;
constructor(nameAnimal: string, nameSnake: string) {
super(nameAnimal);
this.name = nameSnake;
}
toString() {
console.log(`My name is ${this.name} and I'm a snake`);
}
}
class Horse extends Animal {
constructor(name: string) {
super(name);
}
}
// create my objects
let sammy = new Snake('Sammy the Python', 'sssssamy');
let tommy: Animal = new Horse('Tommy the Palomino');
// using method of snake
sammy.toString();
// casting
const animal: Animal = (<Animal>sammy); // or const animal: Animal = sammy as Animal;
// using method of animal
animal.toString()
编辑: 固定输出 输出:
My name is Sammy the Python and I'm a snake
is Animal?: true
is Snake?: true
is Horse?: false
My name is Tommy the Palomino and I'm a animal
is Animal?: true
is Snake?: false
is Horse?: true
My name is sssssamy and I'm a snake
My name is sssssamy and I'm a snake
在这种情况下,我不必打印 My name is ssssamy and I'm an animal? 我认为重载方法,应该调用base中的方法,因为我在snake中使用了强制转换。
【问题讨论】:
标签: typescript inheritance this super