자바스크립트 객체 class 를 쉽게 이해하기 위해
비유한 내용을 작성.
class Car {
constructor(name, price) {
this.name = name;
this.price = price;
this.department = "선릉지점";
}
여기까지는 붕어빵 틀 이라고 생각한다.
일반 객체의 this 와 헷갈릴 수 있는데
여기서 this는 틀을 만드는 것 이라고 생각하면 된다.
그리고 인자 값을 받지않는 this.department는
car 라는 class를 호출한다면 고정값이다.
applyDiscount(discount) {
return this.price * discount;
}
changeDepartment(departmentName) {
this.department = departmentName;
}
}
위에 값들은 봉어빵 틀에서 옵션이라고 생각하면 된다.
class를 호출해도 따로 지정해야한다.
예를들어
const morning = new Car('Morning', 2000000);
console.log(morning);
console.log(morning.name);
console.log(morning.price);
const price = morning.applyDiscount(0.8);
console.log(price);
위의 상황처럼 class 호출후에
applyDiscount 를 따로 호출 해줘야한다.
결론적으로 일반 객체 this 와 class(객체 생성자) 에서의 this 를
차이를 잘 두고 해결하자!