【结论】继承类的 constructor 必须调用 super(...),并且 (!) 一定要在使用 this 之前调用。
【原始代码】
<script>
//父类有加法的方法,子类想要继承父类的加法方法,同时又想要扩展自己的减法方法
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) {
this.x = x;
this.y = y;
}
minus() {
console.log(this.x - this.y);
}
}
var son = new Son(3, 1);
son.minus();
</script>
【运行结果】: