//객체를 만드는 템플릿
1. 생성자 함수
2. 클래스 -->
// static: 정적 프로퍼티
class Fruit{
static count_fruits = 0;
constructor(name, emoji){ //constructor? 자바의 생성자
this.name = name; //자바의 this
this.emoji = emoji;
}
display = () => {
console.log(`${this.name}: ${this.emoji}`);
}
static makebanana() {
return new Fruit(`banana`, `🍌`); //클래스 레벨 메소드에서 this를 참조할 수 없음
}
}
//stw는 Fruit 클래스의 인스턴스
const stw = new Fruit('stw','🍓');
//apple은 Fruit 클래스의 인스턴스
const apple = new Fruit('apple','🍎');
console.log(apple);
console.log(stw);
console.log(stw.name);
console.log(apple.emoji);
apple.display();
// Fruit { display: [Function: display], name: 'apple', emoji: '🍎' }
// Fruit { display: [Function: display], name: 'stw', emoji: '🍓' }
// stw
// 🍎
apple: 🍎
const banana = Fruit.makebanana();
console.log(banana);
console.log(Fruit.count_fruits);
// Fruit { display: [Function: display], name: 'banana', emoji: '🍌' }
// 0
class Dog{
#name;
#color;
constructor(name,color){
this.#name = name;
this.#color = color;
}
get info(){ //getter메소드
return `이름:${this.#name}, 색상:${this.#color}`; //메소드가 아닌 프로퍼티역할
}
set info(value){ //가격을 받아서 처리
console.log('set',value);
this.#name = value;
}
run = () => {
console.log(`${this.#color}색상의 강아지${this.#name}는 달립니다`);
}
#eat = () => {
console.log(`${this.#name}는 먹습니다`);
}
}
const Rucy = new Dog('루시', 'white');
console.log(Rucy); //이름:루시,색상:white x! Dog { run: [Function: run] }
Rucy.run(); //white색상의 강아지 루시는 달립니다
console.log(Rucy.name); //undefined why?
console.log(Rucy.info); //이름:루시, 색상:white
Rucy.info ='뽀미'; //set 뽀미
console.log(Rucy.info); //이름:뽀미, 색상:white