본문 바로가기
JavaScript 기초

[JavaScript] Prototype Chain 이란?

by 개미는뚠뚠딴 2020. 10. 28.
반응형

오늘은 Prototype Chain에 대해서 공부했다. 먼저 MDN에서 Prototype Chain의 개념에 대해서 알아보았다.

 자바스크립트에서 함수는 속성을 가질 수 있으며 모든 함수에는 prototype이라는 특수한 속성이 있다.

각각의 객체는 [[Prototype]]이라는 은닉(private) 속성을 가지는데 자신의 프로토타입이 되는 다른 객체를 가리킨다. 그 객체의 프로토타입 또한 프로토타입을 가지고 있고 이것이 반복되다, 결국 null을 프로토타입으로 가지는 오브젝트에서 끝난다. null은 더 이상의 프로토타입이 없다고 정의되며, 프로토타입 체인의 종점 역할을 한다.

간단한 예시로 알아보겠다. 

function Human(name) {
  this.name = name;
};

Human.prototype.sleep = function(){ // prototype를 이용하여 메서드 생성
  console.log('zzZ 쿨쿨쿨');
}

let h1 = new Human('Leo');
console.log(h1.name); // Leo
h1.sleep(); // zzZ 쿨쿨쿨

h1.__proto__ === Human.prototype; // true
h1.__proto__.__proto__ === Object.prototype // true -> 가장 상위 객체 Object

h1.__proto__.study = function(){
  console.log('공부해요');
}

h1.study(); // 공부해요
h1.__proto__ === Human.prototype; // true

 

h1.__proto__

그렇다면 prototype과 __proto__의 차이는 무엇일까?

  • prototype는 상위 객체(원형 객체)를 뜻하며 함수를 생성할 때 같이 생성된다.
  • __proto__는 생성된 객체의 원형 객체의 prototype를 가리킨다.

Object.create를 이용해 prototype를 복사할 수도 있다.

Human의 prototype를 Student의 prototype로 복사

function Human(name) {
  this.name = name;
};

Human.prototype.sleep = function(){ // prototype를 이용하여 메서드 생성
  console.log('zzZ 쿨쿨쿨');
}

function Student(name){
  this.name = name
};

Student.prototype = Object.create(Human.prototype); // Human의 prototype를 복사

Student.prototype.study = function(){ // prototype를 이용하여 메서드 생성
  console.log('공부해요');
}

let s1 = new Student('Leo'); // Student 객체 생성
s1.study(); // 공부해요 -> student의 prototype
s1.sleep(); // zzZ 쿨쿨쿨 -> Human의 prototype

s1.__proto__ === Human.prototype // false
s1.__proto__ === Student.prototype // true

 

얕은 복사처럼 prototype가 복사되기 때문에 두 prototype는 다르다는 것을 확인할 수 있다. 

이렇게 간단하게 prototype를 복사하는 방법에 대하여 알아보았다.

반응형

댓글