'객체지향 프로그래밍' 이라는 단어에서 '객체'는 데이터 타입obejct를 말하는 것은 아니다.
객체는 영어로 object, 말그대로 사물을 뜻한다.
하지만, 클래스는 결국 { key: value }
처럼 생긴 객체(object)를 잘 설계하기 위한 틀은 맞다.
그런데 이 때의 객체는 특정 로직을 갖고 있는 행동(method)와 변경 가능한 상태(멤버 변수)를 가진다.
원하는 구조의 객체 틀을 짜놓고, 비슷한 모양의 객체를 공장처럼 찍어낼 수 있다.
객체를 매번 만들어서 사용해도 좋지만,
큰 큐모의 객체 이거나 비슷한 모양의 객체를 계속 만들어야 한다면,
class라는 설계도를 통해 만들 수 있다.
앞서 사용했던 레스토랑 직원의 정보 데이터를 가져와보자
const shannon = {
name: "Shannon",
position: ["chief", "supervisor"],
age: 29,
fulltime: false
}
const mike = {
name: "Mike",
position: ["chief", "line-cook manager"],
age: 25,
fulltime: true
}
const ellie = {
name: "Ellie",
position: ["server", "busser"],
age: 32,
fulltime: false
}
const jessica = {
name: "Jessica",
position: ["sever", "hall manager"],
age: 31,
fulltime: true
}
위의 코드는 객체를 사용하지 않고 수많은 변수를 생성하여 작성했던 방식을 객체를 사용하여 간다하게 만든 레스토랑 직원 정보가 담긴 데이터이다.
지금은 직원이 4명뿐이지만, 직원이 20에서 40명 100명이 될지도 모른다.
그럴때마다 위의 코드처럼 작성할 것인가?
각 변수에 담긴 데이터는 값을 제외하고 key
는 모두 동일하다.
name
, position
, age
, fulltime
은 shannon, mike, ellie, jessica 모두가 똑같이 가진 프로퍼티 이름이다.
만약 직원이 30명쯤이라면 위의 코드를 복사 붙여넣기 하여 프로퍼티 값인 value만 직원들의 정보에 맞게 수정하면 된다. 하지만 레스토랑이 분점을 전 세계에 널리 가지고 있다면, 직원이 1억명 이상이라면.... 과연 복사 붙여넣기로 가능할까?
게다가 직원들의 월급을 정확히 계산하기 위해 직책에 따른 임금을 계산하는 메소드를 추가한다. 하지만 직책에 따라 다르기 때문에 각각의 직원들의 직책을 모두 확인하고 따로따로 메소드를 적용시켜야 한다. 이런 직원이 1억명이 넘는다면....
그래서 class가 레스토랑을 도와주러 왔다.
class를 사용하여 직원들의 정보를 다시 정리하자
class Employees {
constructor(name, position, age, fulltime){
this.name = name;
this.position = position;
this.age = age;
this.fulltime = fulltime;
}
monthlyIncome(){
if(this.fulltime === true){
return 1000 * 4
}else {
return 1000 * 2.5
}
}
annualIncome(){
return this.monthlyIncome() * 12;
}
};
const shannon = new Employees("Shannon", ["chief","supervisor"], 29, false);
const mike = new Employees("Mike", ["chief","line-cook manager"], 25, true);
const ellie = new Employees("Ellie", ["server","busser"], 32, false);
const jessica = new Employees("Jessica", ["server","hall manager"], 31, true);
//class 공장에서 래스토랑 직원들의 정보가 잘 찍혀 나왔는지 확인하기
console.log(shannon);
console.log("Montly: ", shannon.monthlyIncome(), "Annual: ", shannon.annualIncome());
console.log(mike);
console.log("Montly: ", mike.monthlyIncome(), "Annual: ", mike.annualIncome());
console.log(ellie);
console.log("Montly: ", ellie.monthlyIncome(), "Annual: ", ellie.annualIncome());
console.log(jessica);
console.log("Montly: ", jessica.monthlyIncome(), "Annual: ", jessica.annualIncome());
monthlyIncome()
, annualIncome()
을 계산하는 메서드도 구현할 수 있다.여기서 this는 뭘까?
객체 내부에서 해당 객체의 프로퍼티에 접근하려면 "this
"라는 키워드를 사용하 수 있다.
그래서monthlyIncome()
메서드에는this.fulltime
을 작성하여fulltime
key에 접근할 수 있다.