用super来调用父类中的构造函数,super必须在子类this之前调用,必须先调用父类中的构造函数,才能使用子类中的构造函数。
class Father {
constructor(x,y){
this.x = x;
this.y = y;
}
sum(){
console.log(this.x + this.y);
}
}
class Son extends Father {
constructor(x,y){
//用super来调用父类中的构造函数
//super必须在子类this之前调用,必须先调用父类中的构造函数,才能使用子类中的构造函数
super(x,y);
this.x = x;
this.y = y;
}
subtract (){
console.log(this.x - this.y);
}
}
var son = new Son(5,3);
son.subtract();
son.sum();