constructor
constructor
메서드는 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.
구문
constructor([arguments]) { ... }
설명
클래스는 constructor
라는 이름을 가진 특별한 메서드를 하나씩만 가질 수 있습니다. 두 개 이상의 constructor
메서드는 SyntaxError
를 유발합니다.
생성자 메서드는 super
키워드를 사용하여 상위 클래스의 생성자 메서드를 호출할 수 있습니다.
생성자 메서드를 지정하지 않은 경우엔 기본 생성자 메서드를 사용합니다.
예제
constructor
메서드 사용하기
class Square extends Polygon {
constructor(length) {
// length로 다각형의 넓이와 높이를 정의하기 위해 부모클래스의 생성자를 호출합니다.
super(length, length);
// Note: 파생 클래스에서, 'this'를 사용하기 전에는 반드시 super()를
// 호출하여야 합니다. 그렇지 않을 경우 참조에러가 발생합니다.
this.name = 'Square';
}
get area() {
return this.height * this.width;
}
set area(value) {
this.area = value;
}
}
다른예제
class Polygon {
constructor() {
this.name = "Polygon";
}
}
class Square extends Polygon {
constructor() {
super();
}
}
class Rectangle {}
Object.setPrototypeOf(Square.prototype, Rectangle.prototype);
console.log(Object.getPrototypeOf(Square.prototype) === Polygon.prototype); //false
console.log(Object.getPrototypeOf(Square.prototype) === Rectangle.prototype); //true
let newInstance = new Square();
console.log(newInstance.name); //Polygon
여기서 Square 클래스의 프로토 타입이 변경되었지만 사각형의 새 인스턴스가 만들어 질 때 이전 기본 클래스 인 Polygon의 생성자가 호출됩니다.
기본 생성자
만약 생성자를 지정하지 않을 경우 기본 생성자 메서드를 사용합니다. 기본 클래스(즉, 아무것도 상속하지 않는 클래스)의 기본 생성자 메서드는 다음과 같습니다.
constructor() {}
파생 클래스의 경우, 기본 생성자는 다음과 같습니다.
constructor(...args) {
super(...args);
}
명세
명세 | 상태 | 설명 |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Constructor Method' in that specification. |
Standard | Initial definition. |
ECMAScript (ECMA-262) The definition of 'Constructor Method' in that specification. |
Living Standard |
브라우저 호환성
BCD tables only load in the browser