ES6 class的继承使用细节

时间:2023-01-10 19:28:40

ES6 class的继承与java的继承大同小异,如果学过java的话应该很容易理解,都是通过extends关键字继承。

class Animal{
constructor(color){
this.color = color;
};
}
class Bear extends Animal{
constructor(){
super();
}
}

其余的就不多说了,这里着重讲一下ES6中super关键字的使用。

ES6子类继承父类,必须在constructor函数的第一行调用super();之后才能使用关键字this,这是因为子类中没有自己的this对象,而是继承父类的this对象,然后才能为这个this添加相应的属性和方法。不然就会报错,相当于Parent.apply(this);而SE5则正好和这个相反,它先创造了自己的this对象,然后才添加父类的方法属性到这个对象里。

super在子类中一般有三种作用

  1. 作为父类的构造函数调用,就是上面所说的那种方法。
  2. 在普通方法中,作为父类的实例调用
  3. 在静态方法中,作为父类调用

在普通方法中调用,此时指向父类的实例

class Animal{
constructor(color){
this.color = color;
}
run(){
return "run";
}
}
class Bear extends Animal{
constructor(){
super();
console.log(super.run());
}
}

在静态方法中调用,此时指向父类

class Animal{
constructor(color){
this.color = color;
}
run(){
return "run";
}
static run(){
return "static run"
}
}
class Bear extends Animal{
constructor(){
super();
console.log(super.run());//run
}
static go(){
super.run();//static run
}
}