객체는 말 그대로 object 사물을 뜻한다
그리고 클래스는 결국 {num :1 } 처럼 생긴 객체를 잘 설계하기 위한 틀이라고 볼 수 있다
객체를 정의,생성 할수도 있지만
클래스로 만들면 여러 객체를 더 쉽게 만들 수 있다
그런데 이 때의 객체는 특정 로직을 갖고 있는 행동(method) 와 변경 가능한 상태를 지닌다
다음 예제를 살펴보자
let ray = {
name: 'Ray',
price: 2000,
carDiscount: function(discount) {
return this.price * discount;
}
}
const rayValue = ray.carDiscount(0.1);
console.log(rayValue) // 200
ray 객체는 3개의 프로퍼티를 가지고 있다
name
price
carDiscount
: 객체의 값에는 함수도 넣을 수 있다ray 의 정보를 또 생성해야 할 때 똑같은 프로퍼티를 가진
객체를 다시 생성해야한다
하지만 ray 정보를 담은 calss 를 생성하여 보다 보기 편하고
간단하게 관리할 수 있다
const cocar = new Car('Cocar', 2000);
new 클래스명()
으로 생성할 수 있다소괄호()
안에는 객체를 생성할 때 전달하고 싶은 값을 넘겨준다
class Car {
constructor(name, price) { // 2.
this.name = name; // 3.
this.price = price;
this.department = "서울지점";
this.salesAmount = 0;
}
}
const cocar = new Car('Cocar', 2000); // 1.
console.log(cocar); //4. { name: 'Cocar', price: 2000, department: '서울지점', salesAmount: 0 }
console.log(cocar.name); //Cocar
console.log(cocar.price); //2000
메서드
라고 한다인스턴스
, -> const cocar = 인스턴스이다new
키워드와 소괄호()
를 사용하여 호출할 수 있다constructor
는 Class에서 필요한 기초 정보를 세팅하는 곳constructor()
메서드에서 name과 price,this
가 필요하다this를 좀 더 살펴보자
class Car {
constructor(name, price) {
this.carName = name;
this.carPrice = price;
this.department = '서울지점';
}
applyDiscount(discount) {
return this.carPrice * discount;
}
}
let carObj = new Car("bmw",2000)
console.log(carObj)
//{
carName: "bmw",
carPrice: 2000,
department: "서울지점"
}
this를 통해서 또 다른 본인의 메서드로 접근 하기 위해서 필요하다
constructor의 매개변수 name,price는
자신의 메서드인 constructor { } 안에서만 쓰일 수 있다
또 다른 자신의 메서드인 applyDiscount { } 와 소통 할 수 있게
let carObj = new Car("bmw",2000) 이처럼
메서드를 만들었을 때 본인 스스로를 의미하는 this
이며,
.carName, .carPrice, .department은 프로퍼티를 의미한다
이곳에 input으로 받은 name,price 값을 저장시킨다
클래스로 또 다른 메서드를 추가해보자
class Car {
constructor(name, price) {
this.carName = name;
this.carPrice = price;
this.department = '서울지점';
}
applyDiscount(discount) {
return this.carPrice * discount;
}
}
let carObj = new Car("bmw",2000)
console.log(carObj)
let carSonata = new Car("sonata",3000)
console.log(carSonata)
console.log(carSonata.applyDiscount(0.1))
{
carName: "bmw",
carPrice: 2000,
department: "서울지점"
}
{
carName: "sonata",
carPrice: 3000,
department: "서울지점"
}
300
결과는 위 처럼 나온다