프로토타입을 더 파고 들어가 보았다...
ES5 문법으로 상속 구현하기
//1. 클래스 생성자 함수
function Season(name, month) {
this.name = name;
this.month = month;
};
//2. 메서드 정의
Season.prototype.weather = function () {
return this.name + ' 은 날씨가 좋아요.'
};
call()
: 부모 클래스의 속성을 호출한다.
function Summer(name, month, fruit) {
Season.call(this, name, month); //부모클래스.call(this, 매개변수)
this.fruit = fruit;
}
이것만으로는 weather()
메서드를 사용할 수 없다.
Season
과 Summer
가 부모-자식 관계라고 할 수 없다.
Object.create()
부모 프로토타입 메서드를 사용하려면 해당 prototype을 참조할 수 있게 해야한다.
Summer.prototype = Object.create(Season.prototype)
//Summer.prototype.constructor이 Season으로 대체됨
Summer.prototype.constructor
> Season(name, month) {
this.name = name;
this.month = month;
}
이것만으로는 문제가 발생한다.
//인스턴스의 constructor이 Summer에서 Season으로 변경
const may = new Summer('may', 5, 'strawberry');
may.constructor === Season
>true
💡
Object.create()
으로 인해...
Summer.prototype의 constructor은 Season이 된다.
Summer을 constructor로 갖는 Summer.prototype은 사라지는 것이다.
그로 인해 Summer의 인스턴스 may의 constructor도 Season이 된다.
//프로토타입 생성자 바꿔주기
Summer.prototype.constructor = Summer;
Summer.prototype.constructor
> Summer(name, month, fruit) {
Season.call(this, name, month);
this.fruit = fruit;
}
부모 클래스 메서드가 호출되는지 확인해보자
console.log(may.weather());
>'may 은 날씨가 좋아요.'
잘 나온다!