大家好,都吃晚饭了吗?我是Kaiqisan,是一个已经走出社恐的一般生徒
今天学TS的时候顺便复习了ES6类的继承,咱来康康吧
感觉没什么多说的,相信大家在学JS之前都一定学过java,这玩意和java的继承几乎一模一样
JS继承有以下特点
我先在这里写一个父类
class person { // 父类
constructor(name, age) {
this.name = name
this.age = age
}
idcard() {
console.log("yes")
}
}
然后在这里写一个子类
// 子类
class stuinfo extends person {
constructor(name, age) {
super(name, age)
}
money() {
console.log("0")
}
idcard() { // 重写了父类的方法
console.log("no")
}
}
const a = new stuinfo("kaiqisan5", 18)
a.idcard() // no
在class 类中,可以使用extends 关键字,实现子类继承父类
语法:
class子类extends 父类{ ... }
和java 一模一样
class stuinfo extends person {
constructor(name, age) {
super(name, age) // 等同于执行父类的构造函数
}
...
}
const b = new stuinfo('chen', 22)
console.log(b) // { name: 'chen', age: 22 }
super方法表示调用父类的构造函数,如果不写super方法则就无法完成继承,从而报错
super关键字还可以获取父类的方法(不准是静态方法)
公式 super.父类方法()
class stuinfo extends person {
constructor(name, age) {
super(name, age)
}
...
getFatherMethod() {
super.idcard() // 直接拿到父类的方法
}
}
const b = new stuinfo('chen', 22)
b.getFatherMethod() // ok
如果出现多重继承(出现孙子类)
super会一直从继承链往上找该方法,如果找到了相应的方法,则停止寻找,一直找到父类。
父类
class Demo1 { // 父类
constructor(name, age) {
this.name = name
this.age = age
}
idcard() {
console.log("yes")
}
}
子类
class Demo2 extends Demo1 { // 父类
constructor(name, age, id) {
super(name, age)
this.id = id
}
idcard() {
console.log("yes2")
}
}
孙子类
class Demo3 extends Demo2 { // 父类
constructor(name, age, id) {
super(name, age, id)
}
idcard() {
console.log("yes3")
}
}
PS:一个父类可以拥有很多个子类,但是一个子类只能拥有一个父类
总结
本文章java选手请跳过!(狗头),js选手请仔细看,其实面向对象应该是每一个程序员的必修课!