07 클래스

7.4 ES6의 클래스 및 클래스 상속

ES5와 ES6의 클래스 문법 비교

ES6에서는 본격적으로 클래스 문법이 도입됐다.

var ES5 = function (name) {
  this.name = name
}
ES5.staticMethod = function () {
  return this.name + ' staticMethod'
}
ES5.prototype.method = function () {
  return this.name + ' method'
}
var es5Instance = new ES5('es5')
console.log(ES5.staticMethod()) // es5 staticMethod
console.log(es5Instance.method()) // es5 method

var ES6 = class {
  constructor (name) {
    this.name = name
  }
  static staticMethod () {
    return this.name + ' staticMethod'
  }
  method () {
    return this.name + ' method'
  }
}
var es6Instance = new ES6('es6')
console.log(ES6.staticMethod()) // es6 staticMethod
console.log(es6Instance.method()) // es6 method

static 키워드는 해당 메서드가 static 메서드임을 알리는 내용으로, ES5 체계에서 생성자 함수에 바로 할당하는 메서드와 동일하게 생성자 함수(클래스) 자신만이 호출할 수 있다.

method라는 이름의 메서드는 자동으로 prototype 객체 내부에 할당되는 메서드다.

ES5.prototype.method와 동일하게, 인스턴스가 프로토타입 체이닝을 통해 마치 자신의 것처럼 호출할 수 있는 메서드다.

ES6의 클래스 상속

var Rectangle = class {
  constructor (width, height) {
    this.width = width
    this.height = height
  }
  getArea () {
    return this.width * this.height
  }
}
var Square = class extends Rectangle {
  constructor (width) {
    super(width, width)
  }
  getArea () {
    console.log('size is :', super.getArea())
  }
}

Square를 Rectangle 클래스를 상속하는 SubClass로 만들기 위해 class 명령어 뒤에 단순히 ‘extends Rectangle’이라는 내용을 추가했다.

이것만으로 상속 관계 설정이 끝난다.

constructor 내부에서는 super라는 키워드를 함수처럼 사용할 수 있는데, 이 함수는 SuperClass의 constructor를 실행한다.

constructor 메서드를 제외한 다른 메서드에서는 super 키워드를 마치 객체처럼 사용할 수 있다. 이때 객체는 SuperClass.prototype을 바라보는데, 호출한 메서드의 this는 ‘super’가 아닌 원래의 this를 그대로 따른다.