ES6
에 등장한 문법class Car {
constructor(name, wheels) { // constructor 추가, 내부에서 선언과 초기화가 된다. 이름은 바꿀 수 없다.
this.name = name;
this.wheels = wheels;
}
start() { // 클래스 메서드 정의
console.log(`${this.wheels}바퀴가 달린 ${this.name}가 앞으로 이동합니다.`)
}
}
// new 키워드를 통해 생성
const x5 = new Car("BMW", 4);
x5.start(); // 결과: 4바퀴가 달린 BMW가 앞으로 이동합니다.
class ElectricCar extends Car { // extends 키워드를 사용하여 상속
constructor(name, wheels, oil) {
super(name, wheels); // 부모 클래스 생성자 호출
this.oil = oil;
}
start() { // Car라는 부모 클래스에서 메서드 호출
super.start();
}
}
const tesla = new ElectricCar("MODEL3", 4, "x");
tesla.start(); // 4바퀴가 달린 MODEL3가 앞으로 이동합니다.
Getter : 클래스 내부에서 정의한 값을 리턴할때 사용한다.
Setter : 클래스 내부에서 정의한 값을 설정할때 사용한다., value를 받아와서 속성을 정의한다. 예를들어 속성값이 음수되는것을 막거나 데이터 유효성 검사 시 사용된다.
class ElectricCar extends Car {
constructor(name, wheels, oil) {
super(name, wheels);
this.oil = oil;
}
start() {
super.start();
}
get wheels() {
return this._wheels;
}
set wheels(value) {
this._wheels = value != 4 ? 0 : value;
}
}
const tesla = new ElectricCar("MODEL3", 3, "x");
tesla.start(); // 결과: 0바퀴가 달린 MODEL3가 앞으로 이동합니다.
public
: 외부에서 접근이 가능.private
: 외부에서 접근이 불가능, 읽기와 변경 불가.class User {
publicField = 10;
#privateField = 3;
}
const user = new User();
console.log(user.publicField); // 결과: 10
console.log(user.privateField); // 결과: undefined
static
: 정적 메서드로, 인스턴스가 아닌 클래스 이름으로 곧바로 호출되는 메서드. 클래스에서 가지고 있는 고유한 값을 지정할때 사용한다. 변경우려가 없거나 공통된 값을 사용할때 쓰인다.class User2 {
static name = "seungit";
constructor(hobby, job) {
this.hobby = hobby;
this.job = job;
}
static sayMyName() {
console.log(`My name is ${User2.name}`);
}
}
const myName = new User2();
console.log(myName.name); // 결과: undefined
User2.sayMyName(); // 결과: My name is seungit