ES6의 class 키워드는 기존의 생성자 함수와 prototype 기반 상속 기능을 좀 더 직관적이고 가독성 좋게 구현할 수 있게 해줍니다. ES6 class의 기본 문법과 상속 기능 구현 방법을 알아봅니다.
function 부모(){} 문법과 동일하게 객체를 생성하는 "기계(생성자 함수)"를 만들 수 있습니다.class 부모 {
constructor() {
this.name = 'Kim';
}
}
const 자식 = new 부모(); // 새 객체 생성
constructor() 내부에서 this.name = 'Kim'을 통해 새 객체의 속성 name에 값을 할당합니다.new 키워드를 사용해 객체를 생성합니다.ES6 class에서는 두 가지 방식으로 상속 가능한 메서드를 추가할 수 있습니다.
class 부모 {
constructor() {
this.name = 'Kim';
this.sayHi = function() {
console.log('hello');
}
}
}
const 자식 = new 부모();
자식.sayHi(); // "hello" 출력
sayHi 함수를 개별적으로 생성합니다.class 부모 {
constructor() {
this.name = 'Kim';
}
sayHi() {
console.log('hello');
}
}
const 자식 = new 부모();
자식.sayHi(); // "hello" 출력
부모.prototype.sayHi = function(){}와 같이 작성할 수도 있습니다.__proto__와 유사한 역할을 하며, 객체의 상속 관계를 확인할 때 유용합니다.class 부모 {
constructor(이름, 나이) {
this.name = 이름;
this.age = 나이;
}
}
const 자식 = new 부모('Park', 30);
'Park'와 30이 각각 name과 age에 할당됩니다.클래스 내부에 여러 메서드를 정의하면, 모두 해당 클래스의 prototype에 추가됩니다.
class 부모 {
constructor(이름, 나이) {
this.name = 이름;
this.age = 나이;
}
sayHi() {
console.log('안녕');
}
sayHello() {
console.log('안녕하세요');
}
}
const 자식 = new 부모('Park', 30);
자식.sayHi(); // "안녕" 출력
자식.sayHello(); // "안녕하세요" 출력
sayHi와 sayHello 메서드는 부모 클래스의 prototype에 정의되어, 모든 인스턴스가 공통으로 사용할 수 있습니다.