Today I Learned - Inheritance Patterns

JS · 2020. 2. 14. 15:07

 

 

__proto__ 와 prototype 프로퍼티

 

__proto__와 prototype은 프로퍼티이며, 이 두 프로퍼티가 가르키는 객체를 prototype 객체라고 한다.

 

__proto__와 prototype에 대한 관계는 다음과 같다.

 

 

 

  • __proto__ 

    • 모든 객체가 갖고 있는 프로퍼티
    • 부모의 prototype 프로퍼티에 대한 정보를 의미 ( prototype link )
  • prototype

    • 함수만 갖고 있는 프로퍼티 ( 함수도 객체이므로 __proto__를 갖고 있음 )
    • 자신의 prototype 객체이며 자식 객체는 이를 참조함

 


 

Object.create()

Object.create = function(obj) {
  function user() {}
  user.prototype = obj;
  return new user();
};

 

Object.create의 내부는 위와 같다.

 

 

위의 내부를 보면 이 abc의 prototype이 인자로 받는 객체(obj)를 참조 하도록 한 후

new 생성자로 새로운 객체를 생성하여 리턴하게 된다.

여기서 유의할 점은 바로 Object.create() 함수의 인자(obj)를 상속을 할 객체 자체가 아닌,

상속할 객체의 prototype에 설정하는 점이다.

 

 

사용법은 아래와 같다.

function user(firstname) {
  this.firstname = firstname;
}

user.prototype = {
  whoIam: function() {
    console.log("I'm " + this.firstname);
  }
}

var Kim = Object.create(user.prototype);
Kim.firstname = "Kim";
Kim.whoIam(); // I'm Kim

 


 

 

 

'JS' 카테고리의 다른 글

TIL - State, life cycle  (0) 2020.03.02
TIL - Component, props  (0) 2020.03.02
Today I Learned - Time complexity  (0) 2020.02.14
Today I Learned - Tree, Binary Search Tree  (0) 2020.02.10
Today I Learned - Graph  (0) 2020.02.10