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
명세
브라우저 호환성
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub
| Desktop | Mobile | Server | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
class | Chrome Full support 42 | Edge Full support Yes | Firefox Full support 45 | IE No support No | Opera Full support 36 | Safari Full support 10.1 | WebView Android Full support 42 | Chrome Android Full support 42 | Edge Mobile Full support Yes | Firefox Android Full support 45 | Opera Android ? | Safari iOS Full support 10.1 | Samsung Internet Android Full support 4.0 | nodejs Full support 6.0.0 |
| Array subclassing | Chrome Full support 43 | Edge ? | Firefox ? | IE No support No | Opera Full support 36 | Safari ? | WebView Android Full support 43 | Chrome Android Full support 43 | Edge Mobile ? | Firefox Android ? | Opera Android ? | Safari iOS ? | Samsung Internet Android Full support 4.0 | nodejs ? |
| Allowed in sloppy mode | Chrome Full support 49 | Edge ? | Firefox ? | IE No support No | Opera Full support 36 | Safari ? | WebView Android Full support 49 | Chrome Android Full support 49 | Edge Mobile ? | Firefox Android ? | Opera Android ? | Safari iOS ? | Samsung Internet Android Full support 5.0 | nodejs ? |
Legend
- Full support
- Full support
- No support
- No support
- Compatibility unknown
- Compatibility unknown