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();
为什么ES6标准中要在构造函数中给super赋值?它正在为类的实例分配一个值。 为什么
super.x
是undefined
而this.x
是3
this
(这是与 new
一起使用的类的实例),因此在超级构造函数和子构造函数中分配 this.x = 1
是相同的。super
是 A.prototype
的缩写,所以 super.x
当然是 undefined
。class A {
#x;
constructor() {
this.#x = 1;
}
get x(){ return this.#x }
set x(v){ this.#x = v }
}
class B extends A {
x;
constructor() {
super();
this.x = 2;
super.x = 3;
console.log(super.x); // undefined
console.log(this.x); // 3
}
}
let b = new B();