javascript prototype vs __proto__
function Person(name, first, second){
this.name = name;
this.first = first;
this.second = second;
}
생성자 함수를 사용하여 객체를 하나 만들면
Person이라는 객체가 만들어지고 또 Person`s prototype이라는 객체가 만들어진다 즉 2개의 객체가 만들어 진다고 생각하자 이 두개의 객체는 서로 관련 연관되어 있다
Person이라는 객체안에는(함수지만 js에서는 함수도 object이다) 내부적으로 prototype이라는 프로퍼티가 생기고 그것은 Person`s prototype을 가리킨다
Person`s property도 어딘가의 Person의 소속이라는 것을 기록해야 한다. 그러기 위해 constructor라는 프로퍼티를 만들고 그 프로퍼티를 Person을 가리킨다.
Person.prototype.sum = function(){}을 정의한다면 Person`s prototype에 sum이라는 함수가 생성이 된다.
var kim = new Person('kim',10,20)이라는 객체(인스턴스)를 만들어 보자 ~!
kim의 객체 안에는 뭐가 있냐하면 name: 'kim', first:10, second:20 그리고..!!!! __proto__가 생겼다.
인스턴스 안에 __proto__
__proto__는 kim이라는 객체를 생성한 Person의 prototype가 된다.
즉 __proto__는 Person`s prototype을 가리킨다
Person.prototype을 통해서도 Person`s prototype에 접근할 수 있고
kim.__proto__를 통해서도 Person`s prototype에 접근할 수 있다.
kim.name 을해보면 kim이라는 객체 안에 name이라는 프로퍼티가 있는지를 먼저 확인한다.
있다면 그 name을 출력하고 끝낸다.
만약에 없다면 !? __proto__가 가리키는 객체(Person`s prototype)에 name이 있는지 없는지를 확인한다.
kim.sum()을 해보면 kim의 객체안에 sum이없고 Person`s prototype에서 찾게 된다.
만약 없다면 그 Person`s prototype의 __proto__가 가리키는 prototype에서 찾게 된다.(프로토체인)