class
선언은 프로토타입 기반 상속을 사용하여, 주어진 이름의 새로운 클래스를 만듭니다.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
클래스 표현을 사용하여 클래스를 정의할 수도 있습니다. 표현식과 달리 선언문으로는 같은 클래스를 다시 선언하면 오류가 발생합니다.
구문
class name [extends] { // class body }
설명
예제
간단한 클래스 선언
다음 예제는 우선 Polygon
클래스를 정의하고, Square
라는 이름의 새로운 클래스가 Polygon
을 상속합니다. 생성자 내부의 super()
는 생성자 내에서만, 그리고 this
키워드를 사용하기 전에만 쓸 수 있다는 점을 주의하세요.
class Polygon {
constructor(height, width) {
this.name = 'Polygon';
this.height = height;
this.width = width;
}
}
class Square extends Polygon {
constructor(length) {
super(length, length);
this.name = 'Square';
}
}
같은 클래스를 두 번 선언하려고 시도할 때
클래스 선언문으로 같은 클래스를 두 번 선언하면 오류가 발생합니다.
class Foo {};
class Foo {}; // Uncaught SyntaxError: Identifier 'Foo' has already been declared
이전에 표현식으로 정의한 경우에도 오류가 발생합니다.
var Foo = class {};
class Foo {}; // Uncaught TypeError: Identifier 'Foo' has already been declared
명세
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Class definitions' in that specification. |
Standard | Initial definition. |
ECMAScript 2016 (ECMA-262) The definition of 'Class definitions' in that specification. |
Standard | |
ECMAScript 2017 (ECMA-262) The definition of 'Class definitions' in that specification. |
Standard | |
ECMAScript (ECMA-262) The definition of 'Class definitions' in that specification. |
Living Standard |
브라우저 호환성
BCD tables only load in the browser