class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
var p = new Point(2,3);
// 1.定义父类
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
// 2.子类继承父类
class ColorPoint extends Point {
constructor(x, y, color) {
super(x, y); // 调用父类的constructor(x, y),注意:返回的是子类的实例
this.color = color;
}
toString() {
return this.color + ' ' + super.toString(); // 调用父类的toString()
}
}
子类:通过’extends’继承了父类的所有属性和方法
super作为函数调用时,指的是父类的构造函数,用来构建自己的this对象,super(x,y),这步,就是利用父类的构造函数,构造自己的this对象,获取与父类实例相同的属性和方法,然后自己传入其他参数,对自己的this对象进行加工,加上子类自己的实例属性和方法,必须调用super方法,且在super在子类当做对象进行调用时,指的是父类的原型对象
.
一言蔽之:就是子类借用父类的构造函数,打造自己的实例对象,并进行属性和方法的扩展,在借用时,修改为自己的this.