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类里面定义的方法能够直接使用
相关文章
相关标签/搜索