JavaScript - Class

HYUK·2022년 12월 29일
0

1. Class

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

2. Class 기본문법

class를 선언만 해준다면 class 객체를 바로 만들 수 있습니다.

class Car {

}

let cocar = new Car();

console.log(cocar); // Car{}

Car라는 이름의 객체가 생성된 걸 확인할 수 있습니다.

3. 생성자(Constructor)

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 키워드로 접근합니다.

4. 인스턴스(Instance)

아래 코드를 참고하며 보겠습니다.

const cocar = new Car('Cocar', 2000);

// new Car('Cocar', 2000); 이 부분이 Instance
  • 인스턴스는 Class 이름에 new를 붙여서 생성합니다.
  • 클래스 이름 우측에 () 괄호를 열고 닫고, 내부에는 constructor 에서 필요한 정보를 인자로 넘겨줍니다.
  • Car클래스의 instance를 cocar라는 변수에 저장했습니다.
  • 이처럼 Car 클래스의 새로운 instance를 생성하려면 new 키워드가 필요합니다. new 키워드는 constructor() 메서드를 호출하고 새로운 instance를 return해줍니다.
  • 'Cocar'라는 String과 2000 이라는 Number를 Car 생성자에 넘겨주었고, name, price 프로퍼티에 각자의 값이 할당되었습니다.

5. 메서드(Method)

메서드는 객체가 프로퍼티 값으로 갖고 있는 함수입니다. 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;
  }
}

Assignment

class 생성을 연습해보겠습니다.

  • 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]; 
     // constructor에있는 멤버변수에 접근하려면 this키워드로 접근해야 함
    }
    add(){
    	return this.Number1 + this.Number2;
    }
    substract(){
    	return this.Number1 - this.Number2;
    }
    multiply(){
    	return this.Number1 * this.Number2;
    }
}
profile
step by step

0개의 댓글