[JavaScript] Prototype Chain


Prototype


JavaScriptのすべてのオブジェクトは、親として機能するオブジェクトに関連付けられています.また、これは、親オブジェクトのプロパティまたはメソッドを継承および使用できるようにするオブジェクト向けの継承概念のようなものです.これらの親は、Prototype(프로토타입) 객체またはPrototype(프로토타입)と呼ばれる.Prototype 객체は、コンストラクション関数によって生成された各オブジェクトに対して共有属性を提供するために使用される.
要するに、簡単に説明すると、モデル青写真を作成する際に使用するプロトタイプオブジェクトです.

コンストラクタ

Prototypeオブジェクトはconstructor propertyを有する.このconstructor propertyとは、オブジェクトの角度から自分のオブジェクトを作成することを意味する.
例えば、Person()生成器関数によって生成されるオブジェクトをfooと呼ぶ.このfooオブジェクトを生成するオブジェクトは、Person()ジェネレータ関数です.このとき、fooオブジェクトについては、自身を生成するオブジェクトがPerson()ジェネレータ関数であり、fooオブジェクトのPrototypeオブジェクトがPerson.prototypeである.したがって、PrototypeオブジェクトPerson.prototypeconstructor propertyは、Person()構造関数を指す.
function Person(name) {
  this.name = name;
}

var foo = new Person('Lee');

// Person() 생성자 함수에 의해 생성된 객체를 생성한 객체는 Person() 생성자 함수이다.
console.log(Person.prototype.constructor === Person);
👉 true

// foo 객체를 생성한 객체는 Person() 생성자 함수이다.
console.log(foo.constructor === Person);
👉 true

// Person() 생성자 함수를 생성한 객체는 Function() 생성자 함수이다.
console.log(Person.constructor === Function);
👉 true

Prototype Chain


オブジェクトのプロパティまたはメソッドにアクセスする場合、JavaScriptは、オブジェクト自体および__proto__が指すリンクを介して、親オブジェクトとしてのプロトタイプまたはメソッドにアクセスできます.
すなわち、あるオブジェクトのpropertyまたはメソッドにアクセスする際に、現在のオブジェクトのpropertyが存在しない場合、__proto__が指すリンクに従って親としてのprototypeオブジェクトのpropertyまたはメソッドがprototypeチェーンであることを順次検索する.
Example
💻 Code
const car = {
    wheels: 4,
    drive(){
        console.log("drive...");
    },
};

const bmw = {
    color: "red",
    navigation: 1,
};

bmw.__proto__=car;

const x5 = {
    color: "white",
    name: "x5",
};

x5.__proto__=bmw;
✔ Result
x5.name
👉 "x5"

x5.color
👉 "white"

x5.navigation
👉 1

x5.drive();
👉 drive...
注意事項
x5
👉 {color: "white", name: "x5"}


for(let p in x5){
    console.log(p);
}
👉 color
👉 name
👉 navigation
👉 wheels
👉 drive


// color와 name을 제외한 나머지들은 Prototpye에서 정의한 property이다.  
for(p in x5){
    if(x5.hasOwnProperty(p)){
        console.log('o', p);
    } else{
        console.log('x', p);
    }
}
👉 o color
👉 o name
👉 x navigation
👉 x wheels
👉 x drive
 

Object.keys(x5);
(2) ["color", "name"]
Object.values(x5);
(2) ["white", "x5"]
💻 コンストラクション関数の使用
const Bmw = function (color){
  this.color = color;
};

Bmw.prototype = {
  constructor: Bmw,
  // 명시하지 않을 경우 z4.constructor === Bmw; 는 false값이 나온다
  // 이런 현상을 방지하기 위해 Prototype으로 덮어씌우지 않고 하나씩 property를 추가하는 것이 좋다
  wheels: 4,
  drive() {
    console.log("drive...");
  },
  navigation: 1,
  stop() {
    console.log("STOP!");
  },
};


const z4 = new Bmw("blue");


z4.stop();
👉 STOP!

z4 instanceof Bmw
👉 true

z4.constructor === Bmw;
👉 true