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

constructor相当于python的initthis 则相当于self

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

类之间通过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
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄