3번 문제입니다.
우선 코드는
class Dog {
constructor(type, color) {
this.type = type;
this.color = color;
}
getAYearOld() {
if (this instanceof Cat) {
return this.age++;
}
}
}
class Cat extends Dog {
constructor(type, color, age) {
super(type, color);
this.age = age;
}
}
const cat1 = new Cat('Nuri', 'yellow', 10);
console.log(cat1); // Cat { type: 'Nuri', color: 'yellow', age: 10 }
console.log(cat1.getAYearOld()); // 10
이렇게 짜서 돌려보았는데 getAYearOld 함수가 작동을 하지 않습니다.
우선 getAYearOld 함수가 Dog 클래스에 prototype으로 들어가있고, Cat 클래스는 Dog 클래스를 extends 했기 때문에
부모 prototype인 getAYearOld 함수를 가져와서 사용할 수 있다는 부분은 이해했습니다.
IDE(WebStrom)에서는 getAYearOld 함수 속의 변수 age를 인식하지 못하고 있는(Unresolved variable age) 상황이지만
어차피 Cat 클래스의 인스턴스 cat1에서 getAYearOld() 함수를 가져온다면 if 조건절 속의 this는 cat1 인스턴스를 가리킬거라 문제는 없다고 판단하였고,
MDN 문서상에서 설명하는 대로 instanceof 연산자의 사용법이 Object instanceof Constructor 형식이라면 더더욱 옳게 코드를 짠 것이라고 생각하였습니다.
하지만 실제로 console.log(cat1.getAYearOld()); 를 통해 getAYearOld 함수를 호출시켜보면 코드가 전혀 작동을 하지 않아서 당황스럽습니다.
한참을 찾아도 이유를 모르겠어서 질문드립니다.