프로토타입은 임의의 다른 객체로 변경할 수 있다.
이것은 부모 객체인 프로토타입을 동적으로 변경할 수 있다는 것을 의미한다.
프로토타입은 생성자 함수 또는 인스턴스에 의해 교체할 수 있다.
생성자 함수에 의한 프로토타입의 교체
인스턴스에 의한 프로토타입의 교체
생성자 함수에 의한 프로토타입 교체와 인스턴스에 의한 프로토타입 교체에는 다음과 같은 차이가 있다.
(이미지 출처: https://velog.io/@rlatp1409/JS-프로토타입-체인-오버라이딩-프로퍼티-섀도잉)
프로토타입으로 교체한 객체 리터럴에 constructor 프로퍼티를 추가하고 생성자 함수의 prototype 프로퍼티를 재설정하여 프로토타입과 생성자함수 간의 파괴되었던 연결을 되살리는 방법은 다음과 같다.
function Person(name) {
this.name = name;
}
const me = new Person('Lee');
// 프로토타입으로 교체할 객체
const parent = {
// constructor 프로퍼티와 생성자 함수 간의 연결을 설정
constructor: Person,
sayHello() {
console.log(`Hi! My name is ${this.name}`);
}
};
// 생성자 함수의 prototype 프로퍼티와 프로토타입 간의 연결을 설정
Person.prototype = parent;
// me 객체의 프로토타입을 parent 객체로 교체한다.
Object.setPrototypeOf(me, parent);
// 위 코드는 아래 코드와 동일하게 동작한다.
// me.__proto__ = parent;
me.sayHello(); // Hi! My name is Lee
// constructor 프로퍼티가 생성자 함수를 가리킨다.
console.log(me.constructor === Person); // true
console.log(me.constructor === Object); // false
// 생성자 함수의 prototype 의 프로퍼티가 교체된 프로토타입을 가리킨다.
console.log(Person.prototype === Object.getPrototypeOf(me); // true