js
1class Parent { 2 constructor() { 3 this.name = 'parent' 4 this.init() 5 } 6 7 init() { 8 this.p1 = 'p1' 9 } 10} 11 12class Child1 extends Parent { 13 constructor() { 14 super() 15 this.name = 'child' 16 } 17 18 init() { 19 super.init() 20 console.log(this.name) 21 this.p2 = 'p2' 22 } 23} 24 25class Child2 extends Parent { 26 constructor() { 27 super() 28 this.name = 'child' 29 this.p2 = 'a' 30 } 31 32 init() { 33 super.init() 34 console.log(this.name) 35 this.p2 = 'p2' 36 } 37} 38 39const c1 = new Child1() 40const c2 = new Child2()
このときc1.p2には'p2'と予想通りの値が格納されているのですが、c2.p2には'a'が格納されています。Child2のinit()が呼ばれているため'p2'という値が格納されるだろうと思っていましたが、なぜこのような違いが生まれるのでしょうか。
また、p2をコンストラクタで初期化し、さらにinit()関数でp2の値を変更するにはどうしたら良いでしょうか。
問題の背景
もともとのコードではChild1のように、constructor()でp2を初期化していませんが、tsがjsにトランスパイルされることにより自動的にconstructor()の中に
js
1this.p2 = void 0
と挿入されるため、Child2のような状況に陥ってしまいました。