티스토리 뷰

이론/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 프로퍼티의 효용

 


[공부 좌표 + 이미지 출처]

생활코딩

함수의 prototype 프로퍼티

 

[참고]

객체의 [[Prototype]]과 __proto__

'이론 > JS' 카테고리의 다른 글

[JS] 객체의 property name(=key)  (0) 2021.02.09
[JS] 객체의 표기법  (0) 2021.02.09
[JS] 객체의 종류  (0) 2021.02.09
[JS] 배열의 추가, 삭제  (0) 2021.02.08
[JS] DOM의 Node 생성, 삽입, 삭제  (0) 2021.02.08
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함