✏
class Fruit {
//필드
//생성자가 제공하는 데이터는 생략이 가능하다.
// name;
// color;
//class가 만들어지자마자 type은 초기화되어 제공된다.
type = "fruit";
constructor(name, color) {
this.name = name;
this.color = color;
}
display = () => {
console.log(`${this.name}: ${this.color}`);
};
}
const apple = new Fruit("apple", "red");
console.log(apple);
//Fruit {
type: 'fruit',
display: [Function: display],
name: 'apple',
color: 'red'
}
✏
const apple = new Fruit("apple", "red");
apple.name = 'orange';
console.log(apple);
//Fruit {
type: 'fruit',
display: [Function: display],
<u>**name: 'orange',**</u>
color: 'red'
}
한번 만들어진 인스턴스 안의 프로퍼티가 변경이 일어났다.
📌 접근제어자
접근제어자를 통해 캡슐화를 할 수 있다.
내부의 프로퍼티를 외부에서 보지 못하게 만든다.
private(#), publick(기본), protected
✏
class Fruit {
#name;
#color;
#type = "fruit";
constructor(name, color) {
this.#name = name;
this.#color = color;
}
display = () => {
console.log(`${this.name}: ${this.color}`);
};
}
const apple = new Fruit("apple", "red");
apple.#name = "orange";
//#feild는 외부에서 접근이 불가능함
console.log(apple);

비공개 필드는 반드시 class 안에서 선언이 되어야 한다.

비공개필드 설정하지 않은 function display만 출력되고, 나머지는 출력되지 않는다.
✏
class Fruit {
#name;
#color;
#type = "fruit";
constructor(name, color) {
this.#name = name;
this.#color = color;
}
#display = () => {
console.log(`${this.name}: ${this.color}`);
};
}
console.log(apple); //Fruit {}
apple.display(); // Error