티스토리 뷰

Prototype

자바스크립트에는 Prototype Link와 Prototype Object가 존재한다. 이를 통들어 Prototype이라고 한다.

 

  • Prototype Object
    function Dog() {}; // 함수 var dogObj = new Dog(); // 함수로 객체를 생성 
    var obj = {}; // var obj = new Object(); 
  • 객체는 언제나 함수로 생성된다.

 

  • 함수가 정의되면 Constructor 자격이 생긴다
  • Constructor 자격이 있어야만 new operator를 통해 객체를 만들어낼 수 있다. new는 함수만 쓸 수 있다. (즉 함수 -> Constructor -> new를 통해 객체 생성 가능)

 

  • 함수가 정의되면 Prototype Object도 같이 생긴다.생성된 함수는 prototype이라는 속성을 통해 Prototype Object로 접근할 수 있다. Prototype Object는 일반적인 객체와 같으며 기본적인 속성으로 constructor__proto__ 를 갖고 있다.는 Prototype Link이다.Prototype Object에 eyes, legs라는 속성 추가됨.
  •  
  • function Dog() {}; Dog.prototype.eyes = 2; Dog.prototype.legs = 4; Dog.prototype ▼{eyes: 2, legs: 4, constructor: ƒ} eyes: 2 legs: 4 ▶ constructor: ƒ Dog() ▶ __proto__: Object
  • constructor는 Prototype Object와 같이 생성됐던 함수를 가리킨다. __proto__
  • Dog.prototype ▼{constructor: ƒ} ▶ constructor: ƒ Dog() ▶ __proto__: Object
  • Prototype Linkpuppy는 함수가 아니므로 puppy.prototype으로 접근 불가. puppy라는 객체에는 eyes라는 속성이 없음에도 puppy.eyes=2 이다. puppy가 가지고 있는 __proto__ 속성(모든 객체가 가지고 있는 속성)을 통해 접근 가능하다. __proto__ 는 객체가 생성될 때 조상이었던 함수의 Prototype Object를 가리킨다. 즉 puppy 객체를 만든 Dog함수의 Prototype Object를 가리킨다.puppy.__proto__ 는 정확히 Dog.prototype과 일치한다. 즉 puppy함수가 eyes를 가지고 있지 않기 때문에 eyes속성을 찾을 때까지 상위 프로토타입을 탐색한다. 만약 찾지 못할 경우 undefined를 리턴한다. __proto__ 를 통해 상위 프로토타입과 연결되어있는 형태를 프로토타입 체인이라고 한다.
  •  
  • 모든 객체는 Object의 자식이기 때문에 Object Prototype Object에 있는 모든 속성을 사용할 수 있다.
  • puppy.__proto__ ▼{eyes: 2, legs: 4, constructor: ƒ} eyes: 2 legs: 4 ▶ constructor: ƒ Dog() ▶ __proto__: Object
  • var puppy = new Dog(); puppy.eyes; // prints 2; puppy ▼ Dog{} ▶ __proto__: Object

Reference: 오승환님 미디엄 블로그

'공부일지(TIL) > JavaScript' 카테고리의 다른 글

ES9 features  (0) 2019.04.16
How JS works? (Asynchronous Programming)  (0) 2019.03.19
Object Oriented Programming: Inheritance(상속), Mixin, Closure, IIFE  (0) 2019.03.11
ES7, ES8  (0) 2019.03.08
pass by reference, shallow copy  (0) 2019.03.08
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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 31
글 보관함