ES6类的继承

ES6 引入了关键字class来定义一个类,constructor是构造方法,this代表实例对象。

constructor相当于python的 init this 则相当于self

类之间通过extends继承,继承父类的所有属性和方法。

super关键字,它代指父类的this对象,子类必须在constructor中调用super()方法,

否则新建实例时会报错,因为子类没有自己的this对象。调用super()得到this,才能进行修改。

class Animal{
  constructor(x){
    this.type = x
  }
  says(say){
    console.log(this.type + " says: " + say )
  }
}



class Dog extends Animal{
  constructor(x){
    super(x);
    this.nickname = '旺财';
  };
}

let cat = new Animal('猫')
cat.says("miao") //猫 says: miao

let dog = new Dog('dog')
dog.says("wangwang") //dog says: wangwang
console.log(dog.nickname) //旺财
console.log(cat.nickname)//undefined
原文地址:https://www.cnblogs.com/qq752059037/p/10868633.html