请看下面代码:
class A {
constructor() {
this.x = 1;
}
}
class B extends A {
constructor() {
super();
this.x = 2;
super.x = 3;
console.log(super.x);
console.log(this.x);
}
}
let b = new B();
上面代码中,super.x = 3与console.log(super.x)两个操作的查找顺序是不一致的
- 子类
B当中的super.p(),就是将super当作一个对象使用。这时,super在普通方法之中,指向A.prototype
- 在子类普通方法中通过
super调用父类的方法时,方法内部的this指向当前的子类实例
- 上面代码中,
super.x赋值为3,这时等同于对this.x赋值为3。而当读取super.x的时候,读的是A.prototype.x,所以返回undefined
- 对目标对象的属性进行操作,目标对象就是this,对
super.x 写,会写入 this
- 从对象中找到属性的定义,在A.prototype中查找
- 更详细segmentfault.com/q/101000002…