9.2.7 객체 프로퍼티 나열 다시 보기

  • ES6 클래스를 설계 의도대로 사용한다면?

    • 데이터 프로퍼티는 항상 인스턴스에 정의해야함

  • 그러나 프로퍼티를 프로토타입에 정의하지 못하도록 강제하는 장치가 없음

    • 확실히 하기 위해 hasOwnProperty 사용하는 것이 좋음

  class Super {
    constructor() {
      this.name = 'Super'; // 인스턴스에 정의
      this.isSuper = true; // 인스턴스에 정의
    }
  }

  // 유효하지만 권장하진 않음
  Super.prototype.sneaky = 'not recommend'; // 프로토타입에 직접 정의

  class Sub extends Super {
    constructor() {
      super();
      this.name = 'Sub'; // 인스턴스에 정의
      this.isSub = true; // 인스턴스에 정의
    }
  }

  const obj = new Sub();

  for (let p in obj)
    console.log(`${p}: ${obj[p]}` + (obj.hasOwnProperty(p) ? '' : ' (inherited)'));

결과

name: Sub
isSuper: true
isSub: true
sneaky: not recommend (inherited)

Last updated