JavaScript & React

02-4 클래스

Jimin Hong 2023. 9. 30. 23:21

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()를 사용한다.

 

 

크롬 브라우저 콘솔 창에서 실행해보자.