class Parent {
constructor(x, y) {
this.x = x;
this.y = y;
this.name = 'ren';
}
saynames() {
console.log(this.name);
}
}
class Child extends Parent {
constructor(x, y, z) {
super(x, y);
this.z = z;
}
}
let child = new Child(...[1, 2, 3]);
console.log(child);
child.saynames();
child输出结果是 Child {x: 1, y: 2, name: “ren”, z: 3},之所以输出这样的结果,其实可以理解为super()函数改变了父类的this指向。而且规定继承就必须使用这个函数,这是因为子类自己的this对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属性和方法,然后再对其进行加工,加上子类自己的实例属性和方法。如果不调用super方法,子类就得不到this对象。
并且此时的sayname方法在child实例的原型的原型上面。
class A {
constructor() {
this.name = 'renjialei';
}
p() {
return this.name;
}
}
class B extends A {
constructor() {
super();
this.name = 'renxiansheng';
console.log(super.p());
}
}
let b = new B();
这里的输出结果是‘renxiansheng’,需要注意的是super作为对象调用时,它代表的是父类的原型。这里之所以能够调用该方法。是因为该方法被定义在父类构造函数的原型上面。输出值为renxiansheng。
class A {
constructor() {
this.x = 1;
}
print() {
console.log(this.x);
}
}
class B extends A {
constructor() {
super();
this.x = 2;
}
m() {
super.print();
}
}
let b = new B();
b.m() // 2
这段代码输出的是2,而不是1.其实原理很简单,使用super将this指向了新生的子类构造函数。也就是说super.print.call(this)。
class A {
constructor() {
this.x = 1;
}
}
class B extends A {
constructor() {
super();
this.x = 2;
super.x = 3;
console.log(super.x); // undefined
console.log(this.x); // 3
}
}
let b = new B();
由于this指向子类实例,所以如果通过super对某个属性赋值,这时super就是this,赋值的属性会变成子类实例的属性。还是那句老话,this指向发生了改变,所以super.x=3就相当于this.x=3.而在读取时找到的又是父类原型上的x属性。
class A {
constructor() {
this.x = 1;
}
static print() {
console.log(this.x);
}
}
class B extends A {
constructor() {
super();
this.x = 2;
}
static m() {
super.print();
}
}
B.x = 3;
B.m() // 3
看一下上面这段代码,在静态方法中调用super对象,它指向的是父类,而不是父类的实例,其中的this指向则指向了子类,而不是子类的实例。