본문 바로가기
study_front/javascript

자바스크립트 객체 상속 (feat. [[Prototype]] 과 __proto__)

by developer_j 2024. 2. 28.
728x90
반응형

 

자바스크립트 객체 상속 (feat. [[Prototype]] 과 __proto__)



자바스크립트 객체에서도 상속관계처럼 다른 객체를 사용할 수 있다.

기본적으로 자바스크립트 객체는 숨김 프로퍼티인 [[Prototype]] 를 가진다.
그리고 [[Prototype]] 프로퍼티의 getter/setter 함수도 존재한다.
숨김 프로퍼티인 [[prototype]] 는 다른 객체로 설정해줄 수 있다. 무조건 객체타입만 가능하며, 객체 이외의 타입인 경우 설정이 무시된다.

이 Prototype 프로퍼티를, 상속관계처럼 사용할 수 있다.


let animal = {
  walk() { // 또는 walk : function() { ... }
    if (!this.isSleeping) {
      alert(`동물이 걸어갑니다.`);
    }
  },
  sleep() { // 또는 sleep : function() { ... }
    this.isSleeping = true;
  }
};

let rabbit = {
  name: "하얀 토끼",
  __proto__: animal  // == rabbit.__proto__ = animal 과 동일 -> setter 함수 호출됨
};



1. [[Prototype]] 설정

위의 예제코드에서, __proto__: animal를 통해
rabbit의 숨김 프로퍼티 [[Prototype]] 에 animal 이라는 객체를 설정해주었다.



2. 상위객체의 프로퍼티 사용

rabbit 객체에 sleep() 함수를 만들어 주지 않았지만, rabbit.sleep() 호출 시 오류없이 진행된다.

 

 

또한
rabbit.sleep(); 호출 전후 차이를 보면 rabbit 객체 안에 isSleeping 프로퍼티가 true로 설정되었다.
여기에서 sleep() 함수 내부의 this 가 animal이 아닌 rabbit 을 가리키고 있음을 알 수 있다.


따라서, 사용하고자 하는 디폴트 객체를 Prototype에 설정해주는 경우
자바의 상속처럼 부모객체의 속성을 그대로 가져다 쓸 수 있으며, 
자식객체에서 함수를 재정의하여 override 해줄 수도 있다.



끝!



** 
 let rabbit.__proto__ = animal 과   let rabbit.animal = animal 이 다른점

let animal = {
  walk() {	// 또는 walk : function() { ... }
    if (!this.isSleeping) {
      alert(`동물이 걸어갑니다.`);
    }
  },
  sleep() { // 또는 sleep : function() { ... }
    this.isSleeping = true;
  }
};

let rabbit = {
  name: "하얀 토끼",
  animal: animal // __proto__ 가 아닌 프로퍼티명으로 설정하는 경우
};


인 경우,



1. 

rabbit.animal.sleep(); 형식으로 사용해야하기 때문에 상속이 아님

rabbit.sleep(); 
VM318:1 Uncaught TypeError: rabbit.sleep is not a function
    at <anonymous>:1:8

 

 


2. 

rabbit.animal.sleep(); 호출 시
isSleeping 프로퍼티 값이, 
rabbit 안이 아닌 rabbit.animal에 생긴다. 즉, this가 가리키는 객체가 rabbit 이 아닌 animal

 

즉 객체 안의 객체일 뿐이당.

728x90
반응형