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();
Why is assigning a value to super in the constructor in the ES6 standard? It is assigning a value to an instance of the class.
Why is super.x undefined while this.x is 3
What happens
this(which is an instance of the class used withnew), so assigningthis.x = 1in a super's constructor and in the child constructor are the same.super.x = 3. ax's SETTER is looked up in the prototype chain starting fromsuper(A.prototype) and when not found,xis assigned tothis. But when readingsuper.x, ax's GETTER is looked up fromsuperand when no found there's no fallback forthissoundefinedis returned ♂️.How to solve (to have (kind of?) multiple same name property per a class in an instance (if needed))
superfor x you should DEFINE the B class withxproperty, otherwisethis.x = 2in the B's constructor will use the setter and won't assignxtothisbut rather tothis.#xin the super.You can also use symbols:
With symbols you could create some generic solution: