JS레플릿 25.Class

송철진·2022년 10월 22일
0

Assignment

MyMath 라는 class를 생성해주세요.
constructor 에서는 숫자 2개를 인자로 받아 프로퍼티로 저장합니다.
총 4개의 메서드를 구현해주세요.

  • getNumber : 두 개의 숫자가 무엇인지 배열로 반환하는 메서드 → ex) [1, 2]
  • add : 두 개의 숫자를 더하는 메서드
  • substract : 두 개의 숫자를 빼는 메서드
  • multiply : 두 개의 숫자를 곱하는 메서드

결과

class MyMath {
  constructor(num1, num2){
    this.number1 = num1;
    this.number2 = num2;
  }
  getNumber(){
    return [this.number1, this.number2];
  }
  add(){
    return this.number1 + this.number2;
  }
  substract(){
    return this.number1 - this.number2;
  }
  multiply(){
    return this.number1 * this.number2;
  }
}
const move = new MyMath(12,89);
console.log(move.getNumber());
console.log(move.add());
console.log(move.substract());
console.log(move.multiply());

Today I Learn

1. Class 란?

  • 객체지향 프로그래밍의 핵심

    • 객체지향 프로그래밍: 프로그램을 객체들로 구성하고, 객체들 간에 서로 상호 작용 하도록 작성하는 방법
    • '객체': 데이터타입이 아닌 사물(object)
  • 객체(object)의 설계도

  • { num: 1 } 처럼 생긴 객체(object)를 잘 설계하기 위한 틀
    이 때의 객체는 특정 로직을 가진 행동(method)변경 가능한 상태(멤버 변수)를 가집니다.

  • 규모가 크거나 모양이 비슷한 객체를 계속 만들어야 한다면,
    객체를 매번 만드는 것보다는 class라는 설계도를 통해 만듭니다.

  • 주의! CSS의 class와 전혀 다릅니다!

  • 객체 내부에서, 해당 객체의 프로퍼티에 접근하려면 "this"라는 키워드를 사용합니다.
    this.프로퍼티

1-1. 매번 객체를 생성한다면?

'ray' 차를 객체로 정의하고 메서드를 호출하여 price프로퍼티에 불러오세요

/*'ray' 차를 객체로 정의*/
// 프로퍼티: name, price, getName, getPrice, applyDiscount
let ray = {  
  name: 'Ray',  
  price: 2000000,   
  getName: function() {  
    return this.name;  
  },   
  getPrice: function() {  
    return this.price;
  // getPrice 메서드에서 this.price 로 price `키`에 접근, 2000000 `값`을 가져옵니다.
  },   
  applyDiscount: function(discount) {  
    return this.price * discount;   
  } 
}
/*객체'ray'에서 getPrice 메서드를 호출*/
const rayPriceByFunction = ray.getPrice();

console.log('함수로 접근 => ' +rayPriceByFunction);
// "함수로 접근 => 2000000"

1-2. 객체의 추가를 클래스로 관리한다면?

차 영업점에서 차를 소개하는 앱서비스를 하려고 합니다
새로운 차가 출시되어 객체를 추가하되, 프로퍼티는 똑같이 구성해야한다면?
필요한 정보를 담은 Car라는 클래스(class)를 생성하여 관리할 수 있습니다.

/*'Car'라는 클래스를 생성*/
// 프로퍼티: name, price, department, salesAmount
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++;
  }
}

2. 생성자(Constructor)

객체(object)와 클래스(class) 가장 큰 차이는 생성자(constructor)함수입니다.

instance: class를 통해 생성된 객체
인스턴스화: class로 객체를 생성하는 과정

/* 인스턴스화 */
const morning = new Car('Morning', 2000000);
// => 인스턴스morning은 클래스Car를 통해 생성된 객체이다
// => 인스턴스가 생성되어 constructor메서드가 호출된 상태다

class는 새로운 instance를 생성할 때마다 constructor() 메서드를 호출합니다.

class Car { // class이름: Car 
  constructor(name, price) { // 멤버변수: name, price
/* class의 실행범위(context)에서 this 는 해당 instance를 의미한다 */
    this.name = name;
    this.price = price;
  }
}

class이름 : 항상 대문자로 시작하고, CamelCase로 작성합니다.

Car class의 instance를 생성할때마다 constructor 메서드가 호출됩니다.

this : class의 실행범위(context)에서 해당 instance를 의미하는 키워드. 멤버변수 접근 시 사용.

멤버 변수 : 클래스 내에서 변경 가능한 상태값이자 class내의 컨텍스트에서 어느 곳에서나 사용할 수 있는 변수. this로 접근.

2-1. 1-2.에서 'morning'이라는 차 등록하기

const morning = new Car('Morning', 2000000);
console.log("인스턴스morning: ", morning);
console.log("인스턴스morning의 멤버변수name: ", morning.name); 
console.log("인스턴스morning의 멤버변수price: ", morning.price);

const price = morning.applyDiscount(0.8); 
console.log("인스턴스morning의 멤버변수price * 0.8: ", price); 

console.log("(판매 전)인스턴스morning의 멤버변수salesAmount: ", 
            morning.salesAmount); 
morning.addSales();
console.log("(판매 후)인스턴스morning의 멤버변수salesAmount: ", 
            morning.salesAmount);

3. 인스턴스(Instance)

인스턴스는 class를 통해 생성된 객체입니다.

  • class의 property이름과 method를 갖습니다.
  • 인스턴스마다 모두 다른 property값을 갖습니다.

생성

  • Class 이름에 new 를 붙입니다.
    • new 키워드는 constructor() 메서드를 호출하고
      새로운 instance를 return해줍니다.
  • 클래스 이름 우측에 () 괄호를 열고 닫고, 내부에는 constructor 에서 필요한 정보를 인자로 넘겨줍니다.

3-1. 새로운 차 등록하기

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

4. 메서드(Methods)

메서드는 객체가 프로퍼티 값으로 갖고 있는 함수입니다.

객체클래스
프로퍼티 간 구분자comma(,)(없음)

4-1. 클래스에 메서드 추가하고 확인하기

Car 객체에 changeDepartment 메서드를 추가했습니다.
changeDepartment 메서드를 호출해보고 해당 인스턴스의 department 정보가 바뀌었는지 확인해 봅시다.

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 Tico = new Car("Tico", 1000000);
console.log("지점명 바꾸기 전: ", Tico);
Tico.changeDepartment("영등포지점")
console.log("지점명 바꾸기 후: ", Tico);

profile
검색하고 기록하며 학습하는 백엔드 개발자

0개의 댓글