1. Class


class는 쉽게 말해 비슷한 모양세의 object를 계속해서 만들 수 있는 ‘설계도'이다. 이는 객체지향 프로그래밍의 핵심이다. 객체지향이란 프로그램을 객체들로 구성하고, 객체들들이 서로 상호작용 하도록 작성하는 것을 말한다.

여기서 말하는 객체는  { num: 1 } 과 같은 데이터 타입을 말하는 것이 아니다. 객체는 영어로 object, 말 그대로 “사물”을 뜻한다. 하지만 class는 결국 { num: 1 } 와 같은 모양세의 객체(object)를 잘 설계하기 위한 틀인 점은 맞다.

그런데 이 때의 객체는 특정 로직을 갖고 있는 행동(method)변경 가능한 상태(member variable)를 가진다. 원하는 구조의 객체 틀을 짜놓고, 비슷한 모양의 객체를 공장처럼 찍어낼 수 있다.

객체를 매번 만들어 사용해도 좋지만 큰 큐모의 객체거나 비슷한 모양의 객체를 계속 만들어야 한다면 class라는 설계도를 통해 만들 수 있다.

// ray object
let ray = {  
  name: 'Ray',  
  price: 2000000,   
  getName: function() {  
    return this.name;  
  },   
  getPrice: function() {  
    return this.price;  
  },   
  applyDiscount: function(discount) {  
    return this.price * discount;   
  } 
}

// 아래와 같은 방식으로 object의 function을 호출할 수 있다.
const rayPriceByFunction = ray.getPrice();
console.log('함수로 접근 => ' +rayPriceByFunction);

위의 ray object는 5개의 property를 갖고 있다. (name ,price ,getName ,getPrice ,applyDiscount ) getName과 getPrice, applyDiscount는 value로 function이 할당되어 있다. 이처럼 object의 value에는 function이 할당될 수 있다.

object 내부에서 property에 접근하려면 this 키워드를 사용할 수 있다. 그래서 getPrice method에서 this.price 로 price key에 접근할 수 있었고, 2000000이라는 value을 갖고 올 수 있다.

만약 위의 코드가 차 영업점 앱서비스에서 사용되며, 새로운 차가 출시되어 object를 추가해야 하지만 property는 동일하게 구성되어야 한다고 가정해보자. 이럴 때엔 차종마다 object를 새롭게 생성해 다량의 코드를 반복 생산하는 대신, 필요한 정보를 담은 Car class를 생성하여 편리하게 관리할 수 있다.

class Car {
  constructor(name, price) {
    this.name = name;
    this.price = price;
    this.department = "선릉지점";
    this.salesAmount = 0;
  }

  applyDiscount(discount) {  
    return this.price * discount;   
  }
  
  addSales() {
    this.salesAmount++;
  }
}

const morning = new Car('Morning', 2000000);
console.log(morning);
console.log(morning.name); // "Morning"
console.log(morning.price); // 2000000

const price = morning.applyDiscount(0.8); 
console.log(price); // 1600000

console.log(morning.salesAmount); // 0
morning.addSales();
console.log(morning.salesAmount); // 1

위 예시와 같이 class car 설계도를 구성한 뒤, 새로운 차종이 발생할 때마다 const morning = new Car('Morning', 2000000); 처럼 활용할 수 있다.





2. Constructor(생성자)


object와 Class는 언뜻 문법이 비슷해 보인다. 이 둘의 가장 큰 차이점으로는 constructor 생성자 함수다. 아래 예시와 같이 Class로 object를 생성하는 과정을 ‘인스턴스화’라고 한다.

const morning = new Car('Morning', 2000000);

또한 Class를 통하여 생성된 object를 instance 인스턴스 라고 부른다. Class는 새로운 instance를 생성할 때마다 constructor() 메서드를 호출한다.

class Car {
  constructor(name, price) {
    this.name = name; // 
    this.price = price;
  }
}

Car는 class이름이다. CamelCase로 작성하는데, 특히 첫글자가 대문자여야 한다. Car class의 instance를 생성할 때마다 constructor method가 호출된다. constructor() method는 name, price 두 개의 argument를 받는다.

constructor() 메서드에 this 키워드가 있다. class의 실행범위(context) 내에서 this 는 해당 instance를 의미한다.

constructor() 에서 인자로 넘어오는 name과 price를 사용해 Car instance의 name, price property에 값을 할당했다. 이렇게 클래스 내에서 name, price와 같이 변경 가능한 상태값이자 class내의 컨텍스트에서 어느 곳에서나 사용할 수 있는 변수를 member variable(멤버변수) 라고 합니다. member variable은 this 키워드로 접근한다.





3. 인스턴스(Instance)

위에서 class instance를 생성했다. instance는 class를 통해 생성된 object이며, class의 property이름과 method를 갖는 object다. instance는 모두 다른 property값을 갖고 있다.

const morning = new Car('Morning', 20000000);
  1. instance는 Class 이름에 new 를 붙여 생성한다. newconstructor() method를 호출하고 새로운 instance를 return해준다.
  2. class 이름 우측에 () 괄호를 열고 닫아, 내부에는 constructor 에서 필요한 정보를 인자로 넘겨준다.
  3. Car class의 instance를 morning 이라는 변수에 저장했다.
  4. 'Morning'이라는 String과 2000000 이라는 Number를 Car 생성자에 넘겨주었고, name, price 프로퍼티에 각자의 값이 할당됐다.

이젠 Car class를 활용해 아래와 같이 새로운 차 또한 만들어 볼 수 있다.

const spaceship = new Car('우주선', 25000000);
console.log(spaceship);
console.log(spaceship.name);
console.log(spaceship.price);
console.log(spaceship.applyDiscount(0.5));



4. Methods


method는 function이다. 그런데 object가 property 값으로 갖고 있는 것을 method라고 부른다. Class의 method는 object의 문법과 동일하다. 다만 object는 property마다 콤마(,)로 구분해줘야 했는데 class는 그렇지 않다.

아래는 Car object에 changeDepartment method를 추가한 예시이다.

class Car {
  constructor(name, price) {
    this.name = name;
    this.price = price;
    this.department = "선릉지점";
  }

  applyDiscount(discount) {
    return this.price * discount;
  }

  changeDepartment(departmentName) {
    this.department = departmentName;
  }
}

const bugatti = new Car("Bugatti", 2000000000)
console.log(bugatti.department)
bugati.changeDepartment("dkdk");
console.log(bugatti.department)
profile
helloworld

0개의 댓글