extends 키워드는 클래스를 다른 클래스의 자식으로 만들기 위해 class 선언 또는 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 ChildClass extends ParentClass { ... }
설명
extends 키워드는 내장 객체뿐만 아니라 사용자 정의 클래스를 하위 클래스로 만들기 위해 사용될 수 있습니다.
확장( 클래스)의 .prototype은 Object 또는 null이어야 합니다.
예
extends 사용하기
첫 번째 예는 Polygon 클래스로부터 Square 클래스를 만듭니다. 이 예는 live demo (source)에서 발췌했습니다.
class Square extends Polygon {
constructor(length) {
// 여기서, length와 함께 부모 클래스의 생성자를 호출
// Polygon의 너비 및 높이가 제공됨
super(length, length);
// 주의: 파생 클래스에서, super()가 먼저 호출되어야 'this'를
// 사용할 수 있습니다. 이를 빼먹으면 참조 오류가 발생합니다.
this.name = 'Square';
}
get area() {
return this.height * this.width;
}
set area(value) {
this.area = value;
}
}
내장 객체에 extends 사용하기
이 예제는 내장 객체 Date를 확장합니다. 이 예제는 live demo (source)에서 발췌했습니다.
class myDate extends Date {
constructor() {
super();
}
getFormattedDate() {
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
return this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear();
}
}
null 확장
null에서 확장은 prototype 객체가 Object.prototype으로부터 상속받지 않은 것을 제외하면 보통 클래스처럼 동작합니다.
class nullExtends extends null {
constructor() {}
}
Object.getPrototypeOf(nullExtends); // Function.prototype
Object.getPrototypeOf(nullExtends.prototype) // null
스펙
| 스펙 | 상태 | 설명 |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'extends' in that specification. |
Standard | 초기 정의. |
| ECMAScript (ECMA-262) The definition of 'extends' in that specification. |
Living Standard |
브라우저 호환성
Update compatibility data on GitHub
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
extends | Chrome
Full support
49
| Edge Full support 13 | Firefox Full support 45 | IE No support No | Opera
Full support
36
| Safari Full support 9 | WebView Android
Full support
49
| Chrome Android
Full support
49
| Firefox Android Full support 45 | Opera Android
Full support
36
| Safari iOS Full support 9 | Samsung Internet Android
Full support
5.0
| nodejs
Full support
6.0.0
|
Legend
- Full support
- Full support
- No support
- No support
- See implementation notes.
- See implementation notes.
- User must explicitly enable this feature.
- User must explicitly enable this feature.