class
키워드 사용
// 클래스 class
class Fruit {
// constructor(생성자): new 키워드로 객체를 생성할때 호출되는 함수
//
constructor(name, emoji) {
this.name = name;
this.emoji = emoji;
}
// function 키워드 사용하면 문법의 오류가 발생
display = () => {
console.log(`${this.name}: ${this.emoji}`);
};
}
인스턴스
// apple은 Fruit 클래스의 인스턴스이다.
const apple = new Fruit('apple', '🍎');
// orange은 Fruit 클래스의 인스턴스이다.
const orange = new Fruit('orange', '🍊');
// obj는 객체이고, 그 어떤 클래스의 인스턴스도 아니다.
const obj = { name: 'ellie' };
class Fruit {
static MAX_FRUITS = 4;
// 생성자: new 키워드로 객체를 생성할때 호출되는 함수
constructor(name, emoji) {
this.name = name;
this.emoji = emoji;
}
// 클래스 레벨의 메서드
static makeRandomFruit() {
// 클래스 레벨의 메서드에서는 this를 참조할 수 없음
// 아무것도 채워지지 않은 탬플릿 상태이기 때문
return new Fruit('banana', '🍌');
}
// 인스턴스 레벨의 메서드
display = () => {
console.log(`${this.name}: ${this.emoji}`);
};
const banana = Fruit.makeRandomFruit();
console.log(banana);
console.log(Fruit.MAX_FRUITS);
class Fruit {
#name; // #을 붙이는 순간 내부에서는 사용이 가능하고 외부에서는 사용불가
#emoji;
#type = '과일';
constructor(name, emoji) {
this.#name = name;
this.#emoji = emoji;
}
#display = () => {
console.log(`${this.#name}: ${this.#emoji}`);
};
}
const apple = new Fruit('apple', '🍎');
//apple.#name = '오렌지';❌ // #field는 외부에서 접근이 불가능함
getter
get
키워드 사용setter
set
키워드 사용class Student {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
get fullName() {
return `${this.lastName} ${this.firstName}`;
}
set fullName(value) {
console.log('set', value);
}
}
const student = new Student('수지', '김');
console.log(student.fullName); // 김 수지
student.fullName = '김철수';
class Animal {
//생성자함수
constructor(color) {
this.color = color;
}
//메소드
eat() {
console.log('먹자!');
}
sleep() {
console.log('잔다');
}
}
// 자식 클래스
class Tiger extends Animal {}
// 상속받은 자식클래스 인스턴스
const tiger = new Tiger('노랑이');
console.log(tiger);
tiger.sleep(); // 잔다
tiger.eat(); // 먹자!
// 자식클래스
class Dog extends Animal {
constructor(color, ownerName) {
// super 부모생성자의 함수 참조
super(color);
// 클래스 필드 추가
this.ownerName = ownerName;
}
// 자식클래스 메서드 추가 가능
play() {
console.log('놀자아~!');
}
// 오버라이딩 overriding : 덮어씌우기
eat() {
super.eat();
console.log('강아지가 먹는다!');
}
}
const dog = new Dog('빨강이', '엘리');
console.log(dog); // Dog { color: '빨강이', ownerName: '엘리' }
dog.sleep(); // 잔다
dog.eat(); // 강아지가 먹는다!
dog.play(); // 놀자아~!