constructor는 클래스의 인스턴스를 생성하고 초기화하는 특별한 메서드입니다.
클래스 정의 내에서 한 번만 사용할 수 있으며, 클래스 인스턴스가 생성될 때 자동으로 호출됩니다.
constructor 메서드는 초기 상태를 설정하거나 인스턴스 프로퍼티를 초기화하는 데 사용될 수 있습니다.
class MyClass {
constructor() {
this.myProperty = 'value';
}
}
get과 set는 접근자(accessor) 메서드입니다.
이들은 객체 프로퍼티에 값을 가져오거나 설정하는 동작을 정의합니다.
get 메서드는 특정 프로퍼티 값을 반환하는 역할을 하고,
set 메서드는 특정 프로퍼티에 값을 할당하는 역할을 합니다.
class MyClass {
constructor() {
this._myProperty = 'value';
}
get myProperty() {
return this._myProperty;
}
set myProperty(newValue) {
this._myProperty = newValue;
}
}
super 키워드는 부모 클래스의 메서드를 호출하는 데 사용됩니다.
이는 주로 부모 클래스의 constructor 메서드를 호출하거나,
부모 클래스의 메서드를 오버라이드(재정의)한 자식 클래스 메서드에서 사용됩니다.
class MyParentClass {
constructor() {
this.myProperty = 'parent value';
}
myMethod() {
console.log('Parent method');
}
}
class MyChildClass extends MyParentClass {
constructor() {
super(); // 부모 클래스의 constructor 메서드를 호출
this.myProperty = 'child value';
}
myMethod() {
super.myMethod(); // 부모 클래스의 myMethod를 호출
console.log('Child method');
}
}
이 세 가지 키워드는 모두 JavaScript 클래스의 중요한 부분이며,
클래스 기반의 객체 지향 프로그래밍 패턴을 구현하는 데 크게 기여합니다.