Skip to content

如何用 class 实现继承?

利用 es6 中的 class 实现继承,首先是父类

js
//父类
class People {
  constructor(name) {
    this.name = name;
  }
  eat() {
    console.log(`${this.name} eat something`);
  }
}

然后通过两个子类通过 extends 继承,注意使用 super 继承父类构造函数

js
//子类
class Student extends People {
  constructor(name, number) {
    super(name);
    this.number = number;
  }
  sayHi() {
    console.log(`姓名${this.name},学号${this.number}`);
  }
}
//子类
class Teacher extends People {
  constructor(name, major) {
    super(name);
    this.major = major;
  }
  teach() {
    console.log(`${this.name} 教 ${this.major}`);
  }
}

实例化输出

js
//实例化
const xialuo = new Student('夏洛', 100);
console.log(xialuo.name, xialuo.number); //夏洛 100
xialuo.sayHi(); //姓名夏洛,学号100
xialuo.eat(); //夏洛 eat something
const wang = new Teacher('王老师', '英语');
wang.teach(); // 王老师 教 英语
xialuo.eat(); // 夏洛 eat something

基于 MIT 许可发布