★ 質問
JavaScriptのプロトタイプチェーンについてはなんとなく理解しているつもりだったのですが、復習がてらに簡単なコードを書いてログを確認したら、Chromeのコンソールで出力される結果と、node環境で出力される結果が異なり、何が正しいのか混乱してしまいました。
以下に載せている最後の行でObject.getPrototypeOf(child)
のログを出力しているのですが、child
のprototypeはParent
なのでしょうか?それとも、Child
なのでしょうか?(質問1)
また、Object.getPrototypeOf(child)
をtypeof
で確認するとobject
と出るので、Constructor Function
ではないのですよね?(質問2)
★ 書いたコード
JavaScript
1//test.js 2 3'use strict'; 4 5class Parent { 6 constructor(name) { 7 this.name = name; 8 } 9 greet1() { 10 console.log('Hi, My name is ' + this.name + '.'); 11 } 12} 13 14class Child extends Parent { 15 constructor(name, age) { 16 super(name); 17 this.age = age; 18 } 19 greet2() { 20 console.log('Hi, My name is ' + this.name + '.'); 21 console.log('I am ' + this.age + ' years old.'); 22 } 23} 24 25const child = new Child('taro', 10); 26console.log(Object.getPrototypeOf(child)); 27
★ 最後の行のログ
Node
$ node test.js > Child {} //最後の行のログ出力結果
Chrome
★ 解決後の補足
以下の場合、どちらも出力結果はChromeコンソール上で{constructor: ƒ}
となりました。
'use strict'; class Child1 { constructor(x){ this.x = x; } } const child1 = new Child1(5); console.log(Object.getPrototypeOf(child1)); class Child2 extends function(){} { constructor(x){ super(); this.x = x; } } const child2 = new Child2(5); console.log(Object.getPrototypeOf(child2));
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/04/09 05:28