프로토타입 체인
상위 객체의 프로퍼티를 호출할 수 있도록 해주는 메커니즘
자바스크립트는 특정 프로퍼티에 접근할 때 해당 객체에 프로퍼티가 없으면 [[Prototype]] 내부 슬롯의 참조를 따라 상위 프로토타입의 프로퍼티를 순차적으로 검색한다.
↓(좀 더 이해하기 쉬운 말)
인스턴스 객체의 key에 접근할 때, 해당 객체에게 key가 없다면 그 다음으로 상위 프로토타입(원형) 속성에서 key가 있는지 확인한다.
없다면 그것을 찾기 위해 더 상위의 프로토타입(부모)에서 찾는다.
function Fruit(name, price){
this.name = name;
this.price = price;
}
Fruit.prototype.itsPrice = function(){
console.log(`${this.name}'s price is ${this.price}`);
}
const apple = new Fruit("apple", 3);
console.log(apple.hasOwnProperty("name")); //true
console.log(Object.getPrototypeOf(apple) === Fruit.prototype); //true
console.log(Object.getPrototypeOf(Fruit.prototype) === Object.prototype); //true
위 코드를 보면 인스턴스 apple이 Object.prototype의 메서드인 hasOwnProperty를 호출하는 것을 볼 수 있다. 즉, apple 객체는 Fruit.prototype과 Object.prototype을 상속받은 것이다.
apple.hasOwnProperty는
apple 객체 -> Fruit.Prototype -> Object.prototype 이 순으로 [[Prototype]] 내부 슬롯의 참조를 따라 자신의 부모 역할을 하는 프로토타입에 해당 프로퍼티가 있는지 검색하여 Object.prototype의 hasOwnProperty 메서드를 사용한 것이다.
프로토타입 체인의 종점은 Object.prototype이다
Object.prototype의 [[Prototype]] 내부 슬롯의 값은 null이다
//생성자 함수에 의한 프로토타입 교체
Fruit.prototype = {
constructor : Person, //Person 생성자 함수가 정의되었다고 가정
newFunc() {
console.log("Change prototype");
}
}
console.log(Fruit.prototype.constructor === Fruit); // false
교체할 경우 constructor 프로퍼티로 기존의 생성자 함수와의 연결했던 부분이 끊어지며 constructor 프로퍼티에 새로운 생성자 함수를 할당해서 다른 생성자 함수와 연결 또한 가능하다
let div = document.createElement('div');
div.__proto__
div.__proto__.__proto__
div.__proto__.__proto__.__proto__
div.__proto__.__proto__.__proto__.__proto__
div.__proto__.__proto__.__proto__.__proto__.__proto__
div.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__
div.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__
//출력
HTMLDivElement {...}
HTMLElement {...}
Element {...}
Node {...}
EventTarget {...}
{...}
null
참조
'CodeStates > JavaScript' 카테고리의 다른 글
Section2 / Unit3 : 비동기 (0) | 2023.05.16 |
---|---|
Section2 / Unit2 : JS 객체 지향 프로그래밍 복습 (0) | 2023.05.12 |
Section2 / Unit2 : 프로토타입과 클래스 (0) | 2023.05.11 |
Section2 / Unit2 : 객체 지향 프로그래밍 (0) | 2023.05.11 |
Section2 / Unit2 : 클래스와 인스턴트 (0) | 2023.05.11 |