.png)
orange, apple, strawberry, watermelon 이라는 객체를 생성한다고 가정해보자. 해당 객체들은 과일이라는 같은 특성을 가지고 있고 name, taste, price 등의 공통 프로퍼티를 갖고 있다. 이 때 각각의 객체를 따로 만들어서 사용한다면 어떨까? 굉장히 비효율적일 것이다.
비슷한 모양의 객체를 계속 만들어야 한다면, 원하는 구조의 객체 틀을 짜놓고 클래스라는 설계도를 통해 공장처럼 찍어낼 수 있다.
즉 클래스는❗️
객체(object)를 효율적으로 설계하기 위한 틀!
new연산자를 통해 클래스로 객체를 생성하는 과정
- 인스턴스 : 클래스를 통해 생성된 객체
const fruit = new Fruit('orange', 'sweet', 2000);
class Fruit {
constructor(name, taste, price) {
this.name = name;
this.taste = taste;
this.price = price;
}
}
constructor() 메서드를 호출한다.constructor() 메서드에 this는 class의 실행범위에서 해당 인스턴스를 의미한다.constructor()에서 인자로 넘어오는 name, taste, price를 사용해 Fruit 인스턴스의 name, taste, price프로퍼티에 값을 할당했다.클래스의 메서드는 객체의 문법과 같다. 하지만 객체는 프로퍼티마다 ,로 구분해줘야 했다면, 클래스는 그렇지 않다.
class Fruit {
constructor(name, taste, price) {
this.name = name;
this.taste = taste;
this.price = price;
}
// 메서드
applyDiscount(discount) {
return this.price * discount;
}
}
메서드 사용은 다음과 같은 방식으로 할 수 있다.
fruit.applyDiscount(0.2);