ES5で子クラスのような動きをするコードでは super() に該当するコードを呼ぶことは必須ではありませんが、ES2015ではそれがないとエラーが発生します。
ES2015の子クラスの constructor() では、なぜ super() を最初に呼ぶ必要があるのでしょうか?
親クラスのコンストラクタが呼ばれていないのは、オブジェクトの状態として変だからでしょうか?
であればなぜ暗黙に呼ばれるのではなく、明示的に記述しなければエラーが発生するようになっているのでしょうか?
ES5
1var Parent = function () { console.log("Parent constructor"); }; 2Parent.prototype.parentMethod = function() { console.log("parentMethod"); } 3 4var Child = function () { console.log("Child constructor"); }; 5Child.prototype = Object.create(Parent.prototype); 6Child.prototype.constructor = Child; 7Child.prototype.childMethod = function() { console.log("childMethod"); } 8 9var c = new Child(); // エラーは発生しない
ES2015
1class Parent { 2 constructor() { console.log("Parent constructor"); } 3 parentMethod() { console.log("parentMethod"); } 4} 5class Child extends Parent { 6 constructor() { console.log("Child constructor"); } // super() を呼んでいないためエラーになる 7 parentMethod() { console.log("childMethod"); } 8} 9var c = new Child(); // ReferenceError: |this| used uninitialized in Child class constructor
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/01/13 06:02