ES6의 클래스 사용 방법
class 키워드로 클래스를 정의한다.
// ES6의 클래스 사용 방법 알아보기
// 크롬 브라우저 콘솔 창에서 실행해보기
class Shape {
static create(x, y) { return new Shape(x, y); }
name = 'Shape';
constructor (x, y) {
this.move(x, y);
}
move(x, y) {
this.x = x;
this.y = y;
}
area() {
return 0;
}
}
var s = new Shape(0, 0);
s.area(); // 0
생성자, 클래스 변수, 클래스 함수 정의에는 변수 선언을 위한 키워드(var, let, const, ...)를 사용하지 않는다.
// 상속 구현
class Circle extends Shape {
constructor(x, y, radius) {
super(x, y);
this.radius = radius;
}
area() {
if (this.radius === 0) return super.area();
return this.radius * this.radius;
}
}
var c = new Circle(0, 0, 10);
c.area(); // 100
extends 키워드를 사용하여 상속을 구현할 수 있다.
상위 클래스 함수를 호출할 때는 super()를 사용한다.

'JavaScript & React' 카테고리의 다른 글
02-6 객체 확장 표현식과 구조 분해 할당 (0) | 2023.10.30 |
---|---|
02-5 화살표 함수 (0) | 2023.10.01 |
02-3 가변 변수와 불변 변수 (0) | 2023.09.28 |
02-2 전개 연산자 (0) | 2023.09.28 |
02-1 템플릿 문자열 (0) | 2023.09.26 |