typescript的super到底是用来干什么的?
本文介绍了typescript的super到底是用来干什么的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
新人刚接触typescript,之前是用javascript的,没接触过java和c#,对于TS里的constructor和super的用法不太理解,官方文档关于super的描述也不是那么详细,请问super到底是干什么的?什么时候会用到super?
class Animal {
name:string;
constructor(theName: string) { this.name = theName; }
move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Snake extends Animal {
constructor(name: string) { super(name); }
move(distanceInMeters = 5) {
console.log("Slithering...");
super.move(distanceInMeters);
}
}
class Horse extends Animal {
constructor(name: string) { super(name); }
move(distanceInMeters = 45) {
console.log("Galloping...");
super.move(distanceInMeters);
}
}
let sam = new Snake("Sammy the Python");
let tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
解决方案
super
实际上用在两种语法中:
constructor
内的super()
: 执行父类的构造函数。必须至少执行一次。一般方法内的
super.method()
: 执行父类的 (未必同名的) 方法。不是必需。
super.method(...)
等价于 父类的构造函数.prototype.method.call(this, ...)
。
你可以把TS编译到没有class的ES5,看看super被变成了什么
这篇关于typescript的super到底是用来干什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文