JavaScript Class 상속하는 방법


ES5 Class 상속


// 기본 클래스
function CalcAdd(options) {
  //
  this.title = options && options.title || 'Calc Add';
  this.calculate = () => {
    console.log(this.constructor.name, "!!!!!");
  };
}

CalcAdd.create = function (options) {
  return new CalcAdd(options);
};

// 프로토타입
CalcAdd.prototype.add = function add() {
  //
};

// 상속받은 클래스
function CalcAddWithDivide(options) {
  //
  const _this = CalcAdd.apply(this, {
    title: 'Calc Add With Divide'
  }) || this; // super(arguments); 와 동일
  _this.calculate = function() {
    console.log(this.constructor.name, "~~~~~~");
  };

  return _this;
};

CalcAddWithDivide.prototype = Object.create(CalcAdd.prototype, {
  constructor: {
    value: CalcAdd,
    enumerable: true,
    writable: true,
    configurable: true
  }
});
CalcAddWithDivide.prototype.constructor = CalcAddWithDivide;

// 추가 프로토타입
CalcAddWithDivide.prototype.divide = function divide() {
  //
};

ES6 Class 상속


// 기본 클래스
class CalcAdd {
  static create(options) {
    return new CalcAdd(options);
  }

  constructor(options) {
    //
    this.title = options && options.title || 'Calc Add';
    this.calculate = () => {
      console.log(this.constructor.name, "!!!!!");
    };
  }

  // 프로토타입
  add() {
    //
  }

  print() {
    console.log(this.constructor.name, this.title);
  }
}

// 상속받은 클래스
class CalcAddWithDivide extends CalcAdd {
  static create(options) {
    return new CalcAddWithDivide(options);
  }

  constructor(options) {
    //
    super(options || {
      title: 'Calc Add With Divide'
    });
    this.calculate = () => {
      console.log(this.constructor.name, "~~~~~~");
    };
  }

  // 추가 프로토타입
  divide() {
    //
  }
}


댓글

이 블로그의 인기 게시물

Next.js에서 자연스러운 Page Transition 방법

[flutter] Android - Package간 sdk version 등이 맞지 않아 오류가 발생하는 경우

[Windows] Chocolatey upgrade