类的继承extends和super关键字

292 阅读2分钟

继承 extends

子类可以继承父类的属性和方法

class Father {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  money() {
    console.log(100);
  }
}

class Son extends Father {}

var xx = new Son(1, 2);
console.log(xx.x); //1
xx.money(); //money

但当子类需要有自己的属性值时:

class Father {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  money() {
    console.log(this.x + this.y);
  }
}
class Son extends Father {
  constructor(x, y) {
    //子类想要有属于自己的属性
    this.x = x;
    this.y = y;
  }
}
var xx = new Son(1, 2);
xx.money(); //报错

由于在子类的对象 xx 中,参数分别传递给子类的构造函数中,这里的 this 属于的是 Son 这个类创建的实例,而使用父类 money 这个方法时,money 中的 this 属于父类创建的实例,两者的 x 和 y 不相匹配,因此会报错。此时我们需要用到 super 关键字,将子类改成:

class Son extends Father {
  constructor(x, y) {
    super(x, y);
  }
}
var xx = new Son(1, 2);
xx.money(); //3

super 关键字是调用父类的构造函数,因此在使用 money 方法时,x 和 y 相匹配

super 关键字调用父类普通函数

class Father {
  say() {
    return "我是爸爸";
  }
}

class Son extends Father {
  say() {
    console.log("我是儿子");
  }
}

var son = new Son();
son.say(); // 输出‘我是儿子’,就近原则,当子类有这个方法时执行子类的这个方法,没有这个方法再向父类查找

我们可以使用 super.方法名() 来调用父类的普通函数

class Son extends Father {
  say() {
    console.log(super.say() + "的儿子");
  }
}

var son = new Son();
son.say(); // 输出‘我是儿子’,就近原则,当子类有这个方法时执行子类的这个方法,没有这个方法再向父类查找

当子类需要继承父类的函数又需要自己创建函数时:

class Father {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  money() {
    console.log(this.x + this.y);
  }
}
class Son extends Father {
  constructor(x, y) {
    super(x, y);
    this.x = x;
    this.y = y;
  }
  subtract() {
    console.log(this.x - this.y);
  }
}
var xx = new Son(1, 2);
xx.money(); //报错

xx.subtract(5, 3); //2

在这里由于 money 方法是父类的,因此需要用 super 调用父类的构造函数,让其参数传递给父类的构造函数。而 subtract 方法是子类的,因此还需要添加 this.x=x this.y=y;

注意:子类在构造函数中使用super,必须放到this前面(必须先调用父类的构造方法,再使用子类的构造方法)