-
카테고리
-
세부 분야
프로그래밍 언어
-
해결 여부
미해결
Object.setPrototype(ray, IdolModel.prototype); 호출 후, ray.dance()가 실행되는 이유를 모르겠어요
24.01.31 22:54 작성 조회수 157
1
섹션3 prototype 강의에서 Object.setPrototype(ray, IdolModel.prototype);을 실행한 후에도 ray.dance()가 실행됩니다.
instanceof를 사용해서 확인한 결과, false가 출력되므로 ray.dance()에서 에러가 발생해야 한다고 생각했는데 제가 잘 못 이해하고 있을까요?
Object.setPrototypeOf(ray, IdolModel.prototype);
console.log(ray.sayHello());
console.log(ray.dance()); //왜 실행되는지?
console.log("ray's type: ",ray instanceof FemaleIdolModel);
답변을 작성해보세요.
0
0
yunjcho
질문자2024.02.02
전체 예제 코드는 아래와 같습니다
function IdolModel(name, year) {
this.name = name;
this.year = year;
}
IdolModel.prototype.sayHello = function() {
return `${this.name} 인사를 합니다.`;
}
function FemaleIdolModel(name, year) {
this.name = name;
this.year = year;
this.dance = function() {
return `${this.name}가 춤을 춥니다.`;
}
}
const gaEul = new IdolModel('가을', 2002);
const ray = new FemaleIdolModel('레이', 2004);
console.log(gaEul.__proto__);
console.log(gaEul.__proto__ === IdolModel.prototype);
console.log(Object.getPrototypeOf(gaEul) === IdolModel.prototype); //gaEul 인스턴스의 __proto__를 가져옴
console.log();
console.log(gaEul.sayHello());
console.log(ray.dance());
console.log(Object.getPrototypeOf(ray) === FemaleIdolModel.prototype);
// console.log(ray.sayHello()); // 해당 메소드가 클래스 안에 없어서 실행 불가
Object.setPrototypeOf(ray, IdolModel.prototype); //이미 생성된 객체에 __proto__를 수정함으로서 이전에 호출하지 못한 함수를 호출 할 수 있게 됨
console.log(ray.sayHello());
console.log(ray.dance()); //?
console.log("ray's type: ",ray instanceof FemaleIdolModel);
console.log(ray.constructor === FemaleIdolModel); //false
console.log(ray.constructor === IdolModel); //true
console.log(Object.getPrototypeOf(ray) === FemaleIdolModel.prototype); //false - 기존 연결이 끊김
console.log(Object.getPrototypeOf(ray) === IdolModel.prototype); //false - 기존 연결이 끊김
console.log(FemaleIdolModel.prototype === IdolModel.prototype); //false
FemaleIdolModel.prototype = IdolModel.prototype;
코드팩토리
지식공유자2024.02.05
this.dance에 함수를 할당할경우 name과 year처럼 인스턴스에 직접 귀속됩니다. 아래 예제를 확인해보시면 조금 더 쉽게 확인 할 수 있습니다. toString()을 실행이 가능하지만 직접 들고있는 프로퍼티인지 확인하는 hasOwnProperty를 사용하면 dance의 경우 true가 나오지만 프로퍼티 체인을 통해 상속 받는중인 toString은 false가 나옵니다.
답변 2