2023-03-31 16:23:22

Class 란?

클래스는 객체를 만들기 위해 사용되는 방법 중 하나로 클래스를 사용하면 코드의 가독성이 좋아지며 상속을 통한 코드의 재사용성을 높여준다.

 

class 기본 문법

class student {
  // class의 생성자 함수
  // constructor() 생성자 함수를 작성하면 빈 생성자 함수가 자동으로 생김
  constructor(age, phone, city) {
    this.age = age;
    this.phone = phone;
    this.city = city;
  }
  getInfo() {
    return (
      "나이 : " + this.age +  "살 핸드폰 번호 : " + this.phone + " 거주지 : " + this.city
    );
  }
}

let st = new student(1, "010-1111-2222", "seoul");

console.log(st);
console.log(st.getInfo());

static

  • static은 정적 메소드로 공용함수를 만들기 위해 사용되며 클래스를 동적 할당 할 때마다 생성 되지 않는다.
class Character {
  constructor(hp, mp, atk) {
    this.hp = hp;
    this.mp = mp;
    this.atk = atk;
  }
  getState() {
    return this.hp + this.mp + this.atk;
  }
  // 정적 메소드 : 일반적으로 공용함수를 만들기 위해 사용
  // 클래스의 인스턴스에서 호출 x
  // static 메소드는 클래스를 동적 할당 할 때마다 생성 되지 않음 (1개만 있음)
  // 인스턴스를 생성할때 더 생성되지 않음
  static getAtk(n) {
    return n.atk;
  }
}

let ca = new Character(100, 100, 100);
console.log(ca);
console.log(ca.getState());
// 이렇게 생성한 인스턴스에서 호출하면 안됨
// console.log(ca.getAtk(1));
console.log(Character.getAtk(ca));

 

getter, setter 

  • getter setter 는 객체의 속성을 읽고 쓸때 사용 하는 함수이다.
  • getter : 값을 호출 할때 사용 
  • setter : 값을 수정 할때 사용 
class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }
  // getter setter
  // get : 값을 호출
  // set : 값을 수정
  // 클래스의 값을 가져오거나 설정할때 getter와 setter 제공
  // 클래스의 값에 접근할때 직접 변수에 접근하는 형태가 아닌 get과 set을 통한 접근방법
  // 내부구조를 캡슐화하는데 좋음
  // 전역적으로 데이터가 사용되지 않게 위험성을 방지
  // 객체지향
  get getName() {
    return "product Name : " + this.name;
  }

  set setPrice(price) {
    this.price = price;
  }
}

let pr = new Product("galaxy note", 1000000);
console.log(pr);
// getter 확인
console.log(pr.getName);
//
pr.setPrice = 2000000;
console.log(pr);

getter를 활용하여 name을 가져오고 setter를 사용하여 price를 변경

 

class의 상속

자식 클래스가 부모 클래스를 상속 받아 부모 클래스의 기능을 사용 할 수 있게 되며 부모 클래스에서 정의된 기능들을 다시 작성하지 않고 사용할 수 있기 때문에 코드의 재사용성이 좋다.

 

class Mother {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  getInfo() {
    return console.log(`이름 : ${this.name} 나이 : ${this.age}`);
  }
}

let temp = new Mother("mother", 1);
temp.getInfo();

// 클래스의 상속
// 자식 클래스가 부모클래스를 상속받아 부모클래스의 기능을 사용
// extends 키워드를 사용해서 클래스를 상속시킬 수 있음
class Child extends Mother {
  // 비워놓으면 constructor가 자동으로 생성
}

let temp2 = new Child("child", 2);
temp2.getInfo();

 

오버라이딩

  • 부모클래스에서 상속받은 함수를 상속받은 자식클래스에서 재정의하여 사용
class Car {
  constructor(name) {
    this.name = name;
    this.speed = 0;
    this.age = 20;
  }
  run(speed) {
    this.speed += speed;
    console.log(`[부모함수] 이름 : ${this.name} 속도 : ${this.speed}`);
  }
  stop() {
    this.speed = 0;
    console.log(`${this.name} 멈춤`);
  }
}

let car = new Car("car");
car.run(10);
car.stop();

// 부모의 함수를 받아 오버라이딩
// 함수를 받아서 기능을 재정의
// run이라는 함수가 없으면 부모에서 상속받은 run 함수 실행
// run 함수가 있어도 재정의 해서 사용 가능 (오버라이딩)
class Tico extends Car {
  run(speed) {
    this.speed = speed;
    console.log(
      `[자식함수] 이름 : ${this.name} 속도 : ${this.speed} [오버라이딩]`
    );
  }
  speak() {
    console.log("빵빵");
  }
  // 부모의 stop을 실행
  // 상속받은 부모의 클래스 키워드로 부모의 함수를 실행 할 수 있음
  // super : 상속받은 부모의 클래스 키워드
  stop() {
    super.stop();
    // 본인의 함수를 실행
    this.speak();
  }
}

let tico = new Tico("tico");
tico.run(10);
tico.stop();

728x90