ご質問の回答としては外してしまうかもしれませんが、プロトタイプチェーン≒継承なので
疑問点はコードの上から三行目のAnimal.Prototypeのところでの関数を設定の仕方
古いブログエントリなどでは以下のようなコードでメンバ定義しているのを見かけます。
javascript
1Animal.prototype = {
2 walk = function() {
3 console.log('トコトコ');
4 }
5/*
6, otherMember
7 */
8}
9
このメンバ定義の方法は、派生オブジェクトではないのでできる方法です。
中盤にあるDog.Prototypeでの関数の設定の仕方が違った
先に述べたメンバの定義方法は継承(派生オブジェクトを定義)する場合には使えません。
javascript
1Dog.prototype = new Animal(); // 継承の定義
2Dog.prototype = { // この代入は「継承の定義」を無効化してしまう
3 bark: function() {
4 console.log('ワンワン! ');
5 }
6}
※派生オブジェクトのメンバは、継承の定義を損なわないように留意します。
prototype
プロパティに個別指定
Object.assign(Obj.prototype, {/* members */})
で指定
なお、コンストラクタ関数は ネームド関数 として宣言しておくと
古典的継承でも instanceof
演算子が使えるようになります。
let d = new Dog();
console.log( d instanceof Dog ); // true
console.log( d instanceof Animal ); // true
古典的継承
javascript
1function Dog() {
2 Animal.apply( this, arguments );
3}
4Dog.prototype = Animal.prototype; // new Animal 以外の方法もある
5Dog.prototype.constructor = Dog; // instanceof Dog を使えるようにする
やや古い Object.create() での継承
javascript
1Dog.prototype = Object.create(Animal.prototype, {
2 constructor: {
3 value: Dog
4 }
5});
6Dog.prototype.bark = function(){/* omitted */}
ES5の継承
Object.assign( Dog.prototype, Animal.prototype );
Dog.prototype.bark = function(){/* omitted */}
ES6の継承(extends
)―MDN 参照。
※ES5 以降は継承も簡便になっています(継承の定義を損なわない)。