function Person() {
this.eyes = 2;
this.nose = 1;
}
let kim = new Person();
let park = new Person();
console.log(kim.eye); // 2
console.log(kim.nose); // 1
console.log(park.eye); // 2
console.log(park.nose); // 1kim과 park은 Person의 eyes와 nose를 공통으로 가지고 있지만, 메모리에는 eyes 2개, nose 2개씩 총 4개가 할당된다. 객체를 100개, 1000개 만들면 메모리에 200개, 2000개가 할당되는 문제가 생긴다.
이러한 문제를 해결하기 위해 Prototype을 사용한다.
function Person() {}
Person.prototype.eyes = 2;
Person.prototype.nose = 1;
console.log(kim.eye); // 2
console.log(kim.nose); // 1
console.log(park.eye); // 2
console.log(park.nose); // 1Person.Prototype이라는 빈 Object가 메모리 어딘가에 존재하고, kim과 park은 그 Object에 있는 값을 사용할 수 있다. 이렇게 되면 eyes와 Nose를 공유하므로 메모리에는 2개만 할당된다.
Prototype은 Prototype Link와 Prototype Object로 이루어져 있다.
객체는 함수로 생성된다.
function Person() {} // 함수
let personObject = new Person(); // 함수로 객체 생성함수가 정의될 때 2가지 일이 동시에 이루어진다.
생성자 자격이란 new를 통해 객체를 생성할 수 있는 자격을 말한다.
함수는 선언되며 생성자 자격을 얻게 된다. 단, 화살표 함수는 생성자 자격을 얻지 않는다.
화살표 함수는 생성자 함수가 아니기 때문이다.
function Person() {} // 생성자 자격 획득
const Person2 = () => {}; // 생성자 자격 획득 X위 이미지처럼 함수가 생성될 때 Person Prototype Object도 함께 생성된다. Person Prototype Object는 prototype으로 접근할 수 있다.
Person Prototype Object는 constructor와 __proto__를 가지고 있으며,
constructor는 해당 prototype을 어떤 함수가 생성했는지를 가리키고 있고, __proto__는 prototype link이다.
예제 코드를 다시 보면
function Person() {}
Person.prototype.eyes = 2;
Person.prototype.nose = 1;Prototype.Object는 객체이므로 속성을 추가/삭제할 수 있으며, kim과 park은 Person 함수를 통해 생성되었기 때문에 eyes와 nose에 접근할 수 있다.
function Person() {}
Person.prototype.eyes = 2;
Person.prototype.nose = 1;
let kim = new Person();
let park = new Person();
console.log(kim.eyes); // => 2kim에는 eyes라는 속성이 없지만 kim.eyes를 실행하면 2라는 값이 나온다. Person Prototype Object의 eyes 속성을 참조한 것이다.
__proto__ 속성은 kim이 Person Prototype Object의 속성을 참조할 수 있게 해준다. prototype 속성과 달리 __proto__ 속성은 모든 객체가 가지고 있다. proto는 객체가 생성될 때 조상이었던 함수의 Prototype Object를 가리킨다.
kim 객체는 Person으로부터 생성되었으니 Person Prototype Object를 가리키고 있는 것이다.
kim은 생성자 함수가 아니기 때문에 prototype 속성은 없다.
kim의 __proto__는 Person Prototype Object를 가리키고 있는데, 이는 kim 객체에 eyes 속성이 없기 때문에 상위 객체로 올라가며 eyes를 찾기 때문이다. Person Prototype Object에도 없으면 undefined를 반환한다.
kim.eyes를 100으로 변경했는데 park.eyes가 그대로인 이유는 kim.__proto__.eyes를 사용하지 않았기 때문이다. kim.eyes = 100은 kim 객체에 eyes 속성을 새로 생성하는 것이다. 체이닝에 의해 kim 객체에 eyes 속성이 있는지부터 확인하기 때문이다. kim.__proto__.eyes는 Person의 eyes 값을 바꾸는 것이다.

