JavaScript_25.Class

🙋🏻‍♀️·2022년 4월 30일
0

wecode

목록 보기
18/40

25-1. Class

클래스는 객체지향 프로그래밍의 핵심이다. 객체지향 프로그램이라는 단어에서 객체는 앞서 배웠던 {num: 1}의 데이터 타입을 말하는 것은 아니다. 객체는 영어로 object, 말그대로 사물을 뜻한다. 하지만 class는 결국 { num: 1 }처럼 생긴 객체(object)를 잘 설계하기 위한 틀은 맞다. 그런데 이 때의 객체는 특정 로직을 갖고 있는 행동(method)와 변경 가능한 상태(멤버 변수)를 가진다. 원하는 구조의 객체 틀을 짜놓고, 비슷한 모양의 객체를 공장처럼 찍어낼 수 있다. 큰 규모의 객체거나 비슷한 모양의 객체를 계속 만들어야 한다면 class라는 설계도를 통해 만들 수 있다. CSS의 class와 전혀 다른 개념이니 유의하기!



📌예시를 통해 알아보자.

'ray'라는 차를 객체로 정의해보자.
ray라는 객체는 5개의 프로퍼티를 갖고 있다. 각 프로퍼티 이름은 아래와 같다.
name
price
getName
getPrice
applyDiscount

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

console.log(ray)

//{
  name: 'Ray',
  price: 2000000,
  getName: ƒ getName(), // 프로퍼티 값에 함수가 할당됨
  getPrice: ƒ getPrice(),
  applyDiscount: ƒ applyDiscount()
} 출력됨

위처럼 객체의 프로퍼티 값에는 함수도 넣을 수 있다.


📌getPrice라는 함수는 다음과 같이 호출할 수 있다.

const rayPriceByFunction = ray.getPrice();
console.log('함수로 접근 => ' +rayPriceByFunction);
let ray = {  
  name: 'Ray',  
  price: 2000000,   
  getName: function() {  
    return this.name;  
  },   
  getPrice: function() {  
    return this.price;  
  },   
  applyDiscount: function(discount) {  
    return this.price * discount;   
  } 
}

const rayPriceByFunction = ray.getPrice();
console.log(rayPriceByFunction);
// 2000000




📌객체 내부에서, 해당 객체의 프로퍼티에 접근하려면 "this"라는 키워드를 사용할 수 있다. 그래서 getPrice 메서드에서 this.priceprice키에 접근할 수 있었고, 2000000 값을 가져올 수 있다.

만약에 위 코드가 차 영업점에서 쓰는 앱서비스에서 사용된다고 생각해보자. 새로운 차가 출시되어 객체를 추가해야 하는데, 프로퍼티는 똑같이 구성되어야 한다. 이럴 때, 차마다 객체를 늘려나가서 코드가 길어지는 것이 아니라, 필요한 정보를 담은 Car라는 ⭐클래스(class)⭐를 생성하여 관리할 수 있다.




🔹class Car { 						//class 생성
  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); 
console.log(morning.price); 

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

console.log(morning.salesAmount); 
morning.addSales();
console.log(morning.salesAmount); 
//
Car {
  name: 'Morning',
  price: 2000000,
  department: '선릉지점',
  salesAmount: 0,
}
'Morning'
2000000
1600000
0
1





25-2. 생성자(Constructor)

객체(object)의 설계도인 클래스(class)는 문법이 비슷하다. 둘의 가장 큰 차이는 constructor라는 생성자 함수이다. 아래와 같이 class로 객체를 생성하는 과정을 '인스턴스화'라고 부른다.

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

class를 통해 생성된 객체를 인스턴스라고 부른다. class는 새로운 instance를 생성할 때마다 constructor()메서드를 호출한다.

class Car { 				// class 이름
 constructor(name,price) {	// 인스턴스
  this.name = name;
  this.price = price;
  }
}
const morning = new Car('Morning', 2000000);
console.log(morning)

• Car는 class이름이다. 항상 대문자로 시작하고, CamelCase로 작성해야한다.
• Car class의 instance를 생성할때마다 constructor 메서드가 호출된다.
constructor() 메서드는 name,price 2개의 argument(인자)를 받는다.
constructor() 메서드에 this 키워드를 사용했다. class의 실행범위(context)에서 this는 해당 instance를 의미한다.
constructor() 에서 인자로 넘어오는 name과 price를 사용해 Car instance의 name,price 프로퍼티에 값을 할당했다.
• 이렇게 클래스 내에서 name,price와 같이 변경 가능한 상태값이자 class내의 컨텍스트에서 어느 곳에서나 사용할 수 있는 변수를 '멤버 변수'라고 부른다.
• 멤버 변수는 this키워드로 접근한다.




25-3. 인스턴스(Instance)

위에서 class instance를 생성했다. 인스턴스(Instance)는 class를 통해 생성된 객체이다. 인스턴스는 class의 property 이름과 method를 갖는 객체이다. 인스턴스 마다 모두 다른 프로퍼티 값을 갖고 있다.

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

• 인스턴스는 class 이름에 new를 붙여서 생성한다.
• 클래스 이름 우측에 ()괄호를 열고 닫고, 내부에는 constructor에서 필요한 정보를 인자로 넘겨준다.
• Car 클래스의 instance를 morning이라는 변수에 저장했다.
• 다시 한번! Car 클래스의 새로운 instance를 생성하려면 new 키워드가 필요하다. new키워드는 constructor() 메서드를 호출하고 새로운 instance를 return 해준다.
Morning이라는 String과 2000000이라는 Number를 Car 생성자에게 넘겨주었고 name,price 프로퍼티에 각자의 값이 할당되었다.

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

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

console.log(morning)
console.log(morning.name);
console.log(morning.price);

//Car {
  name: 'Morning',
  price: 20000000,
  __proto__: { constructor: ƒ Car() }

//'Morning'
20000000




25-4. 메서드(Method)

메서드는 함수이다. 그런데 객체가 프로퍼티 값으로 갖고 있는 것을 메서드라고 부른다. Class의 method는 Object(객체)의 문법과 똑같다. 다만 객체는 프로퍼티마다 comma(,)로 구분해줘야 했지만, 클래스는 그렇지 않다. Car 객체에 changeDepartment메서드를 추가했다.

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

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

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

changeDepartment 메서드를 호출해보고 해당 인스턴스의 department 정보가 바뀌었는지 확인해 봅시다.





✍️Assignment

class 생성을 연습해보자.

• MyMath 라는 class를 생성해주세요.
• constructor 에서는 숫자 2개를 인자로 받아 프로퍼티로 저장합니다.
• 총 4개의 메서드를 구현해주세요.
getNumber : 두 개의 숫자가 무엇인지 배열로 반환하는 메서드 → ex) [1, 2]
add : 두 개의 숫자를 더하는 메서드
substract : 두 개의 숫자를 빼는 메서드
multiply : 두 개의 숫자를 곱하는 메서드

class MyMath {
	constructor(num1,num2) {
     this.num1 = num1
     this.num2 = num2
 }

 getNumber() {
  let arr = [this.num1, this.num2];
  return arr;
}
 add() {
  return this.num1 + this.num2
}
substract() {
 return this.num1 - this.num2
}
multiply() {
 return this.num1 * this.num2 
}
}

0개의 댓글