상위객체 변경

lee jae hwan·2022년 7월 26일

javascript

목록 보기
46/107

new Object();로 객체를 생성하면 자동으로 생성자함수.prototype객체와 상속관계가 형성됨을 알았다.

상위객체의 변경

let animal = {
  eats: true
};
let rabbit = {
  jumps: true
};

상위객체를 변경하기위해 [[prototype]]숨김속성을 설정하는 방법은 어떻게 되는가?

자바스크립트는 [[prototype]]숨김속성을 대신해서 __proto__라는 일반속성을 지원한다.

rabbit.__proto__ = animal;

이제 rabbit의 상위객체는 Object.prototype객체에서 animal로 변경되었다.
위 코드는 객체생성후 상위객체를 변경한것임을 확인하자.

let animal = {
  eats: true
};
let rabbit = {  
  __proto__:animal
};
console.log(rabbit.eats);

rabbit객체는 생성과 동시에 animal과 상속관계를 형성한다. 위의 생성후 상속관계를 변경한것과 다르다.



자바스크립트에서 __proto__일반속성은 [[prototype]]의 접근자프로퍼티로 구현되어있다. (getter, setter프로퍼티)

__proto__는 버그로인한 문제가 발생할 수 있기 때문에 가급적 사용하지 않는것이 좋으며 현재는 대체할 메소드(Object.setPrototypeOf)가 지원되고있다.

하지만 __proto__속성이 워낙 널리 쓰이고있기 때문에 사용법은 알고있는것이 좋다.




아래사할들은 참고로 알아두자

__proto__속성의 제한사항

let rabbit = {
  jumps: true,
};
let longEar = {
  earLength: 10,
  __proto__: rabbit
};
rabbit.__proto__ = longEar;

순환상속은 에러를 발생시킨다.

let rabbit = {
  jumps: true,
};
console.log(rabbit.__proto__); // Object
rabbit.__proto__ = 'abcd';
console.log(rabbit.__proto__); // Object

__proto__의 값은 객체나 null만 가능 다른 자료형은 무시된다.

0개의 댓글