class field 오버라이딩

lee jae hwan·2022년 7월 30일

javascript

목록 보기
66/107
class Animal {
  name = 'animal';
  constructor() {
    console.log(this.name);
  }
}
let animal = new Animal(); // animal

class field는 클래스가 생성될때 할당되고 constructor가 수행될때 가장 먼저 객체에 바인딩된다.


class Animal {
  name = 'animal';
  constructor() {
    console.log(this.name); 
  }
}
class Rabbit extends Animal {
  name = 'rabbit';
  constructor(){
     super();
  }
}
let rabbit = new Rabbit(); // animal
console.log(rabbit.name); // rabbit

하위클래스의 객체생성과정을 살펴보자

  1. new Rabbit();으로 Rabbit클래스의 constructor가 호출되면 Rabbit클래스의 빈객체가 생성된다. (console.log(this instanceof Rabbit)으로 알수 있다)

  2. super(); 호출된다.
    상위constructor는 생성객체로부터 호출된다. 주의

  3. 빈객체에 상위클래스 클래스필드들이 추가되고 상위constructor가 수행된다.

  4. Rabbit의 클래스필드가 추가되고 하위constructor가 수행된다.

위의경우 Animal constructor에서 클래스 필드인 name프로퍼티를 추가하고 'animal'로 설정한후 Rabbit constructor에서 클래스필드인 name프로퍼티를 'rabbit'으로 변경한다.

0개의 댓글