es6之继承extends

一个类可以去继承其他类里面的东西,这里定义一个叫Person的类,然后在constructor里面添加两个参数:name和birthday;

下面再添加一个自定义的方法intro,这个方法就是简单地返回this.name和this.birthday;
class Person{
  constructor(name,birthday){
    this.name = name;
    this.birthday= birthday;
  }
  intro(){
    return '${this.name},${this.birthday}';
  }
}

 然后再定一个Chef类,使用extends去继承Person这个类,如果这个类里面有constructor方法,就要在constructor方法里面使用super,它可以去调用父类里面的东西

class Chef extends Person{
  constructor(name,birthday){
    super(name,birthday);
  }
}
 
let zhangsan = new Chef('zhangsan','1988-04-01');
console.log(zhangsan.intro()); //zhangsan,1988-04-01

 因为Chef这个类继承了Person类,所以在Person类里面定义的方法可以直接使用

原文地址:https://www.cnblogs.com/shj-com/p/15153888.html