클래스 소개

  • 객체를 손쉽게 만들수 있는 템플릿
  • 객체지향 프로그래밍
  • class 키워드 사용

// 클래스 class
class Fruit {
  // constructor(생성자): new 키워드로 객체를 생성할때 호출되는 함수
  // 
  constructor(name, emoji) {
    this.name = name;
    this.emoji = emoji;
  }
  // function 키워드 사용하면 문법의 오류가 발생
  display = () => {
    console.log(`${this.name}: ${this.emoji}`);
  };
}

인스턴스

  • 클래스를 통해 만들어진 객체를 인스턴스라고 함
  • new연산자와 함께 클래스 이름을 호출하면 클래스의 인스턴스가 생성된다.
// apple은 Fruit 클래스의 인스턴스이다.
const apple = new Fruit('apple', '🍎');
// orange은 Fruit 클래스의 인스턴스이다.
const orange = new Fruit('orange', '🍊');
// obj는 객체이고, 그 어떤 클래스의 인스턴스도 아니다.
const obj = { name: 'ellie' };

static 정적 프로퍼티, 메서드

  • 클래스에 한번만 정의하고 재사용 할 수 있음
class Fruit {
  static MAX_FRUITS = 4;
  // 생성자: new 키워드로 객체를 생성할때 호출되는 함수
  constructor(name, emoji) {
    this.name = name;
    this.emoji = emoji;
  }
  // 클래스 레벨의 메서드
  static makeRandomFruit() {
    // 클래스 레벨의 메서드에서는 this를 참조할 수 없음
    // 아무것도 채워지지 않은 탬플릿 상태이기 때문
    return new Fruit('banana', '🍌');
  }
 // 인스턴스 레벨의 메서드
  display = () => {
    console.log(`${this.name}: ${this.emoji}`);
  };

const banana = Fruit.makeRandomFruit();
console.log(banana);
console.log(Fruit.MAX_FRUITS);

field

  • 접근제어자를 이용해 캡슐화
  • 내부상으로 필요한 데이터를 외부에서 사용할 수 없도록 하는 것
  • private(#), public(기본), protected
class Fruit {
  #name; // #을 붙이는 순간 내부에서는 사용이 가능하고 외부에서는 사용불가
  #emoji;
  #type = '과일';
  constructor(name, emoji) {
    this.#name = name;
    this.#emoji = emoji;
  }
  #display = () => {
    console.log(`${this.#name}: ${this.#emoji}`);
  };
}

const apple = new Fruit('apple', '🍎');
//apple.#name = '오렌지';❌ // #field는 외부에서 접근이 불가능함

접근자 프로퍼티 getter,setter

  • 변수처럼 보이지만 함수
  • 함수처럼 정의되며 호출은 데이터 프로퍼티에 접근하는 것 처럼 호출할 수 있다.

getter

  • 원하는 함수 앞에 get 키워드 사용
  • 프로퍼티를 읽으려고 할 때 실행

setter

  • 원하는 함수 앞에 set 키워드 사용
  • 프로퍼티에 값을 할당하려 할 때 실행
class Student {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  get fullName() {
    return `${this.lastName} ${this.firstName}`;
  }

  set fullName(value) {
    console.log('set', value);
  }
}
const student = new Student('수지', '김');
console.log(student.fullName); // 김 수지
student.fullName = '김철수';

클래스 상속

  • 상속을 사용하여 기존 클래스를 다른 클래스로 확장
  • extrnd : 상속 받는 자식 클래스를 정의
  • super : 부모 클래스의 생성자를 호출
  • overriding : 부모 클래스의 메서드를 재정의 하는것
class Animal {
  //생성자함수
  constructor(color) {
    this.color = color;
  }
  //메소드
  eat() {
    console.log('먹자!');
  }
  sleep() {
    console.log('잔다');
  }
}
// 자식 클래스
class Tiger extends Animal {}
// 상속받은 자식클래스 인스턴스
const tiger = new Tiger('노랑이');
console.log(tiger);
tiger.sleep(); // 잔다
tiger.eat(); // 먹자!

// 자식클래스
class Dog extends Animal {
  constructor(color, ownerName) {
    // super 부모생성자의 함수 참조
    super(color);
    // 클래스 필드 추가
    this.ownerName = ownerName;
  }
  // 자식클래스 메서드 추가 가능
  play() {
    console.log('놀자아~!');
  }

  // 오버라이딩 overriding : 덮어씌우기
  eat() {
    super.eat();
    console.log('강아지가 먹는다!');
  }
}
const dog = new Dog('빨강이', '엘리');
console.log(dog); // Dog { color: '빨강이', ownerName: '엘리' }
dog.sleep(); // 잔다
dog.eat(); // 강아지가 먹는다!
dog.play(); // 놀자아~!

0개의 댓글