Prototype vs Class
- 객체지향언어(Java, Python 등등)에서는 class의 개념이 빠질 수 없다.
- Java Script는 Prototype 언어이다.
- class가 없으니 상속기능도 없다.
- Prototype 기반으로 흉내내기는 가능하다.
- ES6에 class 문법이 추가되었다. (Java Script가 클래스 기반으로 바뀐건 아니다.)
- 아래 코드는 메모리에 눈 2개 코 2개 총 4개의 객체가 할당된다.
function Person() {
this.eyes = 2;
this.nose = 1;
}
let kim = new Person();
let lee = new Person();
console.log(kim.eyes); // 2
console.log(kim.nose); // 1
console.log(lee.eyes); // 2
console.log(lee.nose); // 1
- Prototype으로 해결 가능
- Person.prototype 이라는 객체가 어딘가에 존재하고 Person 함수로 만들어진 객체들은 그 어딘가에 존재하는 Person.prototype 객체를 사용할 수 있다.
- 즉, eyes와 nose를 어느 빈 공간에 넣어두고 갖다가 쓰는 개념.
function Person() {}
Person.prototype.eyes = 2;
Person.prototype.nose = 1;
let kim = new Person();
let lee = new Person();
console.log(kim.eyes); // 2
console.log(kim.nose); // 1
console.log(lee.eyes); // 2
console.log(lee.nose); // 1
Prototype Object
- 객체는 항상 함수로 생성된다.
- 해당 함수에 constructor(생성자) 자격 부여
- new 키워드를 통해 객체를 생성할 수 있다.
- Prototype Object는 일반적인 객체와 같고 기본적인 속성으로 constructor와 __proto__를 갖는다.
- constructor는 Prototype Object와 같이 생성된 함수를 가리킨다.
- __proto__는 Prototype Link이다.
Prototype Link
- proto 속성은 모든 객체가 가지고 있는 속성이다.
- __proto__는 생성될 때의 함수를 가리킨다.
- 속성을 찾을때까지 상위 프로토타입을 검색한다(Prototype Chain)
3줄 요약
- Java Script는 함수를 생성하면 Prototype이라는 객체를 갖는다.
- Prototype Object는 Constructor라는 속성을 갖는데 이는 자신을 만들어낸 함수를 참조한다.
- Java Script는 객체를 생성하면 __proto__라는 속성을 갖게 되는데 이는 자신을 만들어낸 함수(객체)의 Prototype을 참조한다.