Class를 사용하는 가장 큰 이유는 재사용성입니다. 원하는 구조의 객체를 생성하는 틀을 짜놓고, 이것을 통해서 비슷한 모양의 객체를 공장처럼 찍어낼 수 있습니다.
특히, 큰 큐모의 객체이거나 비슷한 모양의 객체를 계속 만들어야 한다면, class는 반복 사용되는 설계도의 역할을 하게 됩니다.
const wecar = {
name: 'Wecar',
price: 1000,
getName: function() {
return this.name;
},
getPrice: function() {
return this.price;
},
applyDiscount: function(discount) {
return this.price * discount;
}
}
위에서 getPrice 라는 함수는 다음과 같이 호출할 수 있습니다.
const wecarPriceByFunction = wecar.getPrice();
console.log('함수로 접근 => ' + wecarPriceByFunction); //1000
프로퍼티 명으로도 접근이 가능합니다. 아래 코드내용 입니다.
const wecarPriceByPropertyName = wecar.price;
console.log('프로퍼티명으로 접근 => ' + wecarPriceByPropertyName); //1000
class를 선언만 해준다면 class 객체를 바로 만들 수 있습니다.
class Car {
}
let cocar = new Car();
console.log(cocar); // Car{}
Car라는 이름의 객체가 생성된 걸 확인할 수 있습니다.
Constructor(생성자)를 이용하면 class 객체의 초기 값을 설정해 줄 수 있습니다. class 내부에서 Constructor는 한 개만 존재할 수 있으며, 2번 이상 사용 시 Syntax Error가 발생할 수 있습니다.
class Car {
constructor(name, price) {
this.name = name;
this.price = price;
this.department = "선릉지점";
this.salesAmount = 0;
}
const cocar = new Car('Cocar', 2000) // 인스턴스 설정
console.log(cocar);
// Car{name: 'Cocar', price: 2000, department: '선릉지점', salesAmount:0}
console.log(cocar.name);
//Cocar
console.log(cocar.price);
//2000
- Car는 class 이름입니다. class명은 PascalCase로 작성해야 합니다.
- Car class의 instance를 생성할때마다 constructor 메서드가 호출됩니다.
- Car class의 constructor() 메서드는 name, price 2개의 argument(인자)를 받고 있습니다.
- constructor() 메서드에 this 키워드를 사용했습니다. class의 실행범위(context)에서 this 는 해당 instance를 의미합니다.
- constructor() 에서 인자로 넘어오는 name과 price를 사용해 Car class를 통해 생성되는 instance의 name, price 프로퍼티에 값을 할당합니다.
- 이렇게 클래스 내에서 name, price와 같이 변경 가능한 상태값이자 class내의 컨텍스트에서 어느 곳에서나 사용할 수 있는 변수를 '멤버 변수'라고 부릅니다.
- 멤버 변수는 this 키워드로 접근합니다.
아래 코드를 참고하며 보겠습니다.
const cocar = new Car('Cocar', 2000);
// new Car('Cocar', 2000); 이 부분이 Instance
메서드는 객체가 프로퍼티 값으로 갖고 있는 함수입니다. Class의 method는 Object(객체)의 문법과 똑같습니다. 다만 객체는 프로퍼티마다 comma(,)로 구분해줘야 했지만, 클래스는 그렇지 않습니다.Car 객체에 changeDepartment 메서드를 추가했습니다.
class Car {
constructor(name, price) {
this.name = name;
this.price = price;
this.department = "선릉지점";
}
applyDiscount(discount) { // Method
return this.price * discount;
}
changeDepartment(departmentName) { // Method
this.department = departmentName;
}
}
class MyMath{
constructor(num1, num2){
this.Number1 = num1; // 멤버변수
this.Number2 = num2; // 멤버변수
}
getNumber(){
return [this.Number1, this.Number2];
// constructor에있는 멤버변수에 접근하려면 this키워드로 접근해야 함
}
add(){
return this.Number1 + this.Number2;
}
substract(){
return this.Number1 - this.Number2;
}
multiply(){
return this.Number1 * this.Number2;
}
}