
자바스크립트는 객체지향 언어이나 전통적 객체지향과 차이가 존재함. Java 등의 클래스 기반 객체지향과 달리 프로토타입 기반 객체지향 사용.
⇒ 이를 보완하기 위해 ES6에서 클래스 문법 도입
자바스크립트 클래스란? 새로운 객체지향 개념이 아닌 프로토타입 기반 상속을 쉽게 사용할 수 있는 문법적 설탕. 기존 개념을 쉽게 활용하도록 도움
class ClassName {
constructor() {
// 생성자 메서드
}
method1() {
// 메서드 1
}
method2() {
// 메서드 2
}
}
new 키워드로 호출. 매개변수로 인스턴스 속성 초기화 가능생성자 메서드 constructor: 클래스의 인스턴스를 생성하고 초기화하는 특별한 메서드
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
getInfo() {
return `${this.name}, ${this.age}`;
}
}
const personC = new Person("철수", 30);
console.log(personC.getInfo()); // 출력: 철수, 30
function PersonF(name, age) {
this.name = name;
this.age = age;
this.getInfo = function() {
console.log(`${this.name}, ${this.age}`);
};
}
const personF = new PersonF("철수", 20);
PersonF.prototype.getInfo = function() {
console.log(`${this.name}, ${this.age}`);
};
getInfo 메서드: 프로토타입 객체에 저장. 모든 인스턴스가 이 메서드 공유. 메모리 사용량 감소
class PersonC {
constructor(name, age) {
this.name = name;
this.age = age;
}
getInfo() {
return `${this.name}, ${this.age}`;
}
}
const personC = new PersonC("영희", 30);
constructor 메서드 인스턴스 생성 시 자동 호출. 인스턴스의 초기 속성 설정 역할function 키워드를, 클래스는 class 키워드를 사용한다.constructor 메서드 내에서 정의한다.prototype 객체를 통해 메서드를 추가하지만, 클래스는 내부에 직접 메서드를 정의한다.클래스와 생성자 함수: 둘 다 자바스크립트의 객체지향 특성 반영. ES6 이후 클래스 사용 권장