Constructor和其中的super

Constructor

constructor 是和 class 一起用来创建和初始化对象的特殊方法。--mdn

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

super

super用来继承父类的构造函数或者拿来调用父类的方法

class Cat { 
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    console.log(this.name + ' makes a noise.');
  }
}

class Lion extends Cat {//Lion继承了Cat
  speak() {
    super.speak();//拿来调用父类中的方法
    super(name);//拿来继承父类中的构造函数
    console.log(this.name + ' roars.');//如果不使用super就在子类的constructor中调用this会报错,找不到this
  }
}
  • 在下图中可以看到,要使用super继承父类的构造器,才能在new的时候,同时使用父类和子类的构造函数。


    Constructor和其中的super_第1张图片
    example

小节:super一般有两种方法

  • super(a,b):作为函数调用,作用:继承父类的构造函数
  • super.speak():作为对象调用,作用:调用父类中的函数

你可能感兴趣的:(Constructor和其中的super)