ES6 클래스 정의 및 상속


ES6에서는 OOP 스타일의 클래스를 정의하여 사용할 수 있습니다. 형식은 다른 프로그래밍 언어의 클래스 정의와 유사하여 다른 프로그래밍 언어의 경험이 있다면 금방 이해할 수 있습니다.

클래스 정의

// Class 정의
class Alice {
  constructor (id) {
    this.id = id
    this.x = 0;
    this.y = 0;
  }
  
  walk (x, y) {
    this.x = x
    this.y = y
  }
}

// Class를 사용한 객체 생성
const alice = new Alice(1234);
alice.walk(10, 10);

상속

class Alice extends Human {
  constructor (id, gender, height) {
    super(id)
    this.gender = gender
    this.height = height
  }
}

Static 멤버

class Main extends React.Component {
  static defaultProps = {
    name: "default"
  }
}

Getter / Setter

getter 및 setter 는 동적 프로퍼티 할당을 위한 접근자 프로퍼티입니다.

특정 프로퍼티에 값을 할당할 때에는 setter 가 호출되며, 값을 평가할 경우에는 getter가 호출됩니다.

예제

class Rectangle {
  constructor (width, height) {
    this._width = width
    this._height = height
  }
  
  set width (width) { this._width = width }
  get width ()      { return this._width }
  set height (height) { this._height = height }
  get height ()       { return this._height }
  get area () { return this._width * this._height }
}

const rect = new Rectangle(10, 5)

console.log(rect.area) // 50
SHARE