[JavaScript 프로토타입] Learn more... ES5 문법으로 상속 구현하기

young·2022년 5월 26일
0

5/25~6/22 Section 2 TIL

목록 보기
6/27

✅ TIL

프로토타입을 더 파고 들어가 보았다...
ES5 문법으로 상속 구현하기


✔️ ES5 문법으로 상속 구현하기

1. 부모 클래스 생성

//1. 클래스 생성자 함수
function Season(name, month) {
  this.name = name;
  this.month = month;
};
//2. 메서드 정의
Season.prototype.weather = function () {
  return this.name + ' 은 날씨가 좋아요.'
};

2. 자식 클래스 생성

call()

: 부모 클래스의 속성을 호출한다.

function Summer(name, month, fruit) {
  Season.call(this, name, month); //부모클래스.call(this, 매개변수)
  this.fruit = fruit;
}

이것만으로는 weather() 메서드를 사용할 수 없다.
SeasonSummer가 부모-자식 관계라고 할 수 없다.

3. 상속

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;
}

4. 메서드 호출 확인해 보기

부모 클래스 메서드가 호출되는지 확인해보자

console.log(may.weather());
>'may 은 날씨가 좋아요.'

잘 나온다!

profile
즐겁게 공부하고 꾸준히 기록하는 나의 프론트엔드 공부일지

0개의 댓글