1. Prototype이란?
- Javascript에서는 객체를 상속하기 위하여 프로토타입이라는 방식을 사용한다.
- JavaScript는 흔히 '프로토타입 기반 언어(prototype-based language)'라 불린다. 모든 객체들이 메소드와 속성들을 상속 받기 위한 템플릿으로써 '프로토타입 객체(prototype object)'를 가진다는 의미이다.
- 프로토타입 객체도 또 다시 상위 프로토타입 객체로부터 메소드와 속성을 상속 받을 수도 있다.. 이를 '프로토타입 체인(prototype chain)'이라 부르며 다른 객체에 정의된 메소드와 속성을 한 객체에서 사용할 수 있도록 해준다.

- 상속되는 속성과 메소드들은 각 객체가 아니라 객체의 생성자의 prototype이라는 속성에 정의되어 있다.
- 객체의 prototype과 생성자의 prototype 의 차이를 인지하는 것이 중요하다. 전자는 개별 객체의 속성이고, 후자는 생성자의 속성이다.
- 프로토타입에 메소드를 추가하면 해당 생성자로 생성된 모든 객체에서 사용 가능하다.



2. Prototype 예제
Prototype 속성 생성
function Person() {}
Person.prototype.eyes = 1;
Person.prototype.nose = 2;
const korean = new Person();
const chinese = new Person();
console.log(korean.eyes);
console.log(chinese.nose);
/************결과값************
1
2
******************************/
Prototype 메소드 생성
function Person() {}
const korean = new Person();
const chinese = new Person();
Person.prototype.eat = function (food) {
console.log(food);
};
Person.prototype.breathe = function () {
console.log("후하후하~");
};
korean.eat("밥");
chinese.breathe();
/************결과값************
밥
후하후하~
******************************/
*.constructor로 원본 생성자 함수를 확인할 수 있다..
console.log(korean.constructor);
console.log(Person.constructor);
console.log(Function.constructor);
/************결과값************
[Function: Person]
[Function: Function]
[Function: Function]
******************************/
*.prototype으로 정의된 속성이나 메소드를 확인할 수 있다.
console.log(korean.prototype);
console.log(Person.prototype);
/************결과값************
undefined
{
eyes: 1,
nose: 2,
eat: [Function (anonymous)],
breathe: [Function (anonymous)]
}
******************************/
확인해보면 위에서 사용했던 속성과 메소드들이 모두 Person이 가진 prototype 속성과 메소드임을 알 수 있다.
[참조문서]
https://developer.mozilla.org/ko/docs/Learn/JavaScript/Objects/Object_prototypes
반응형
'JAVASCRIPT > ES6' 카테고리의 다른 글
| [JS] Currying (0) | 2023.02.03 |
|---|---|
| [JS] Spread Syntax (전개 구문, 전개 연산자) (0) | 2023.02.02 |
| [JS] 일급 객체와 일급 함수 (First-class Object & Function) (0) | 2023.01.30 |
| [JS] JSON (JavaScript Object Notation) (0) | 2023.01.29 |
| [JS] 구조 분해 할당(Destructuring Assignment) (0) | 2023.01.25 |
댓글