Class inheritance
extends connstructor super
Example 1:
Father {class
constructor () {}
Money () {
the console.log ( "10000 block" );
}
}
// subclass inherits the parent class using the extends Son Father
class {} Father Son extends
var SS = new new Father ();
SS .money ();
// 10000 block
Example 2:
class Fa { constructor(x, y){ this.x = x; this.y = y; } sum(){ var su = this.x + this.y; console.log(su); } } class Son extends Fa{ constructor(x, y){ // constructor用于存放类的共有属性 this.x = x; this.y = y; } } var son = new Son(1, 2); son.sum(); // 输出:Uncaught ReferenceError: Must call super constructor in derived
class before accessing 'this' or returning from derived constructor
the reason:
Parameters (1,2) son instance of an object is in fact points to a subclass of Son constructor (x, y) is not the parent class Fa constructor (x, y) can not use sum () method.
Improve:
super keyword is used to access and to call on the parent class constructor. You can call the constructor of the parent class, you can also call a normal function of the parent class
{Fa of the class
constructor (X, Y) {
in this.x = X;
this.y from Y =;
}
SUM () {
var = SU + in this.x this.y from;
the console.log (SU);
}
}
class the extends Son {FA
constructor (X, Y) {
Super (X, Y); // constructor is called the parent class constructor
}
}
var new new Son = Son (. 1, 2);
son.sum ();
//. 3