이론/JS
[JS] 함수의 prototype 프로퍼티
millfeel1298
2021. 2. 9. 12:53
| 프로퍼티 | 설명 |
| prototype | - 모든 함수는 prototype 프로퍼티를 갖는다. - 함수의 prototype은 constructor 프로퍼티 하나만 있는 객체를 가리킨다. - constructor은 함수 자신을 가리킨다. |
function Rabbit(){
// prototype = {constructor: Rabbit};
}

| 프로퍼티 | 설명 |
| [[Prototype]] | - 객체는 명세서에서 명명한 [[Prototype]]이라는 숨김 프로퍼티를 갖는다. - 생성자 함수로 만든 객체인 경우, 생성자 함수의 prototype 프로퍼티에 연결된 객체의 값을 [[Prototype]]에 연결한다. |
let animal = {
eats: true
};
function Rabbit(name) {
this.name = name;
}
Rabbit.prototype = animal;
let rabbit = new Rabbit("White Rabbit"); // rabbit.__proto__ == animal
alert( rabbit.eats ); // true

자바스크립트는 constructor 값을 보장하지 않는다.
function User(){};

User.prototype = {name : 'mill'}
prototype의 값을 덮어씌워 버리면서 constructor이 없어져버렸다.

그렇다면 constructor를 유지하려면 어떻게 해야할까?
"prototype" 전체를 덮어쓰지 말고, 기본 "prototype"에 원하는 프로퍼티를 추가/제거해야 한다.
function User(){};
User.prototype.warning = function(){
alert('경고');
}

Prototype 프로퍼티의 효용
[공부 좌표 + 이미지 출처]
생활코딩
[참고]