2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptのプロトタイプチェーン(継承)について

Last updated at Posted at 2018-02-15

JavaScriptのプロトタイプチェーンについて、いまいちよく分かっていなかったのですが
以下の2つを読んで、
どうやってプロトタイプチェーンを作るのかと、
プロトタイプチェーンがあるときのプロパティ解決の考え方が分かりました。

結局のところ
MyDog < Dog < Animal < Object
のようなプロトタイプチェーンを作りたいときは以下のようにすればいいようですね。

サンプルコード

MyDog.js
function Animal() {

}

function Dog() {

}

Dog.prototype = Object.create(Animal.prototype, {
    constructor: {
        value: Dog,
        enumerable: false
    }
});

function MyDog() {

}

MyDog.prototype = Object.create(Dog.prototype, {
    constructor: {
        value: MyDog,
        enumerable: false
    }
});

動作確認

var myDog = new MyDog();
console.log(myDog.constructor); // MyDog
console.log(Object.getPrototypeOf(myDog)); // MyDog

console.log(
    Object.getPrototypeOf(
        Object.getPrototypeOf(myDog))); // Dog

console.log(
    Object.getPrototypeOf(
        Object.getPrototypeOf(
            Object.getPrototypeOf(myDog)))); // Animal

console.log(
    Object.getPrototypeOf(
        Object.getPrototypeOf(
            Object.getPrototypeOf(
                Object.getPrototypeOf(myDog))))); // Object

console.log(myDog instanceof MyDog); // true
console.log(myDog instanceof Dog); // true
console.log(myDog instanceof Animal); // true
console.log(myDog instanceof Object); // true

上記から分かるように多重継承はできないようですね。
また、es6のclass継承では同じような処理をしているようですね。
続き JavaScriptのプロトタイプチェーン(継承)について ES6のclass

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?