LoginSignup
0
0

More than 1 year has passed since last update.

JavaScriptのプロトタイプ継承について(1)

Posted at

はじめに

こちらの記事は長くなりますので複数回に分けます。

[[Prototype]]について

javascriptにおいてオブジェクトは隠しプロパティとして[[Prototype]]を持っています。これはnullまたは別のオブジェクトを参照します。隠しプロパティをコンソールで確かめてみましょう。

JS
let animal = {
    eats: true
};

console.log(animal);

スクリーンショット 2021-10-22 23.18.42.png

プロパティ [Prototype]]が存在していることが確認できます。
プロパティ [[Prototype]] は内部であり隠されていますが、セットする多くの方法があります。

JS
let animal = {
    eats: true
};
let giraff = {
    neck: "long"
};

giraff.__proto__ = animal;
console.log(giraff.neck); // =>long
console.log(giraff.eats); // =>true

giraff.__proto__ = animalとすることでgiraffのプロトタイプにanimal をセットしています。したがってgiraffでもanimalのプロパティを見つけることができます。
イラストで確認しましょう。
スクリーンショット 2021-10-22 23.46.04.png

giraff.eatsを読もうとしたとき、それはgiraffにはないので、JavaScriptは[[Prototype]]参照に従って、animalの中でそれを見つけます(左から右に向かいます)。このとき "animalはgiraffのプロトタイプ"または"giraffがプロトタイプ的にanimalを継承している" と呼ぶことができます。

もしanimalがプロパティにthisを持っていたとしましょう。この時thisはどちらのオブジェクトに対応するでしょうか。

JS
let animal = {
    eats: true,
    voice: 'wan',
    bark() {
        this.Barking = true
    }
};
let giraff = {
    neck: "long",
    __proto__: animal
};

giraff.bark();
console.log(giraff.Barking);// =>true
console.log(animal.Barking);// =>undefined

thisはプロトタイプによる影響を持ったく受けません。thisはあくまで呼び出し元のオブジェクトになります。上記のコードの場合まず
1. giraffがanimalを継承している(__proto__: animal)
2. giraff.bark();でプロパティにBarkingをセット(継承しているのでanimalのメソッドを利用した)
3. giraffがbarkメソッドの呼び出し元なのでthisはこれに対応する
4. 結果として、メソッドは共有されますが、オブジェクトの状態は共有されないのでanimalにはBarkingプロパティはセットされていない

次回に続く。。。。

参考

Udemy: 【JS】ガチで学びたい人のためのJavaScriptメカニズム
現代の JavaScript チュートリアル:https://ja.javascript.info/logical-operators

0
0
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
0
0