class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return `(x: ${this.x}, y: ${this.y})`;
}
}
class ColorPoint extends Point {
constructor(x, y, color) {
super(x, y);
this.color = color;
}
toString() {
return this.color + ' ' + super.toString();
}
}
let cp = new ColorPoint(1, 1, 'red');
console.log(cp.toString());
console.log(cp instanceof Point);
console.log(cp instanceof ColorPoint);
//-----------继承父类静态方法---------//
class A {
constructor() {
this.p = 2;
}
static hello() {
console.log('hello world');
}
}
class B extends A {
get m() {
return super.p;
}
get n() {
return super.x;
}
}
B.hello();
let b = new B();
console.log(b.m);//由于super指向父类的原型对象,所以定义在父类实例上的方法或者属性,是无法通过super调用的.
A.prototype.x = 2;
console.log(b.n);//属性x是定义在A.prototype上面的,所以super.x可以去到它的值.
//----------super 和 this-----------//
//ES6规定 在子类普通方法中通过super调用父类方法时,方法内部的this指向的是当前子类实例.
class C {
constructor() {
this.x = 1;
}
print(){
console.log(this.x);
}
}
class D extends C{
constructor(){
super();
this.x=2;
}
m(){
super.print();
}
}
let d=new D();
d.print();
//在子类的静态方法中通过super调用父类方法时,方法内部的this指向当前的子类,而不是子类的实例;
class E{
constructor(){
this.x=1;
}
static print(){
console.log(this.y);//这里指向的是类的静态属性
}
}
class F extends E{
constructor(){
super();
this.x=2;
}
static m(){
super.print();
}
}
E.y=10;//给父类静态属性赋值后,子类的静态属性也自动继承了.
F.m()
console