241031 클래스

수달·2024년 10월 31일

클래스

1. ES6 Class 문법: 2015년 전까지는

1.1 객체지향언어: 전통적인 객체지향과는 조금 다름

  • Java: 클래스 기반의 객체 지향
  • JavaScript: 프로토타입 기반의 객체 지향

2. Class

  • 프로토타입을 쉽게 사용하기 위한 Sugar Syntax (설탕 문법)

3. 일급 객체 (번외)

  • 정의: 객체는 아니지만 객체로 취급이 되는 특징, 특성, 것
  • 변수에 할당이 가능해야 함
  • 함수의 인자로 전달할 수 있어야 함
  • 함수의 반환 값으로 사용될 수 있어야 함
  • 동적으로 생성이 가능해야 됨
// 변수에 할당 가능 -> 함수 표현식
const sum = function () {};

// 함수의 인자로 전달할 수 있어야 함
function greet(callback) {
  callback();
}

greet(() => {
  console.log("hello");
});

// 함수의 반환 값으로 사용할 수 있어야 함
function outer() {
  return function () {
    console.log("inner");
  };
}

const a = outer();
a();

// 동적으로 생성 가능해야 함
const dynamicFunc = new Function("name", "return '안녕하세요, ' + name");
console.log(dynamicFunc("기수"));

3. class

3.1 class 정의 방법
3.2 class 상속 방법

  • 객체들 간의 관계를 구축하는 방법

3.3 정적 메서드 정의 방법

  • 프로토타입이 아닌 함수 자체에 메서드를 설정
  • 인스턴스를 생성하지 않고 사용할 수 있는 메서드
  • 인스턴스에서 메서드를 호출하지 않고 클래스 내부에서 메서드를 호출하는 경우

✨
https://yeonhapark.github.io/blog/javascript-class-static-method/

✔️ 인스턴스 메서드로 정의

  • 객체를 통해 접근
  • add 메서드를 호출하려면 MathUtils 인스턴스가 필요
class MathUtils {
  // 인스턴스 메서드로 정의
  add(n1, n2) {
    return n1 + n1;
  }
}

const math = new MathUtils();
const sum = math.add(10, 20);
console.log(sum);

✔️ static 으로 선언

  • 클래스 자체를 통해 접근
  • 클래스 이름을 통해 바로 접근 가능
class MathUtils {
  static PI = 3.14;
// static으로 선언
  static add(n1, n2) {
    return n1 + n1;
  }
}

const sum = MathUtils.add(10, 20);
console.log(MathUtils.PI);

function Mathss() {}
Mathss.add = function (a, b) {
  return a + b;
};
console.log(Mathss.add(10, 20));

인스턴스 메서드 체이닝

  • 객체의 여러 메서드를 한 줄에서 순차적으로 연결해 호출하는 방식
  • 메서드를 체이닝할 때, 이전 메서드가 호출된 인스턴스(객체)를 반환하면 다음 메서드를 이어서 호출할 수 있음
  • 체이닝을 가능하게 하려면 메서드가 항상 그 객체 자신(인스턴스)를 반환해야 함
  • 쉽게 말해, 체이닝하려면 메서드가 실행된 후 return this; 구문으로 그 객체(인스턴스) 자체를 다시 돌려줘야 함

연습문제 8. 인스턴스 메서드 체이닝

Builder 클래스를 만들어, 여러 메서드를 체이닝할 수 있도록 하세요.

class Builder {
  constructor() {
    this.value = ""; // 초기 문자열은 빈 문자열로 설정
  }

  append(text) {
    this.value += text; // 전달받은 text를 value에 더해 줌
    return this; // 중요: this를 통해 Builder 인스턴스 반환하여 체이닝을 가능하게 함
  }

  getValue() {
    return this.value; // 최종 문자열을 반환함
  }
}

const builder = new Builder();	// Builder 클래스의 인스턴스 생성해 builder 변수에 할당
const result = builder.append("Hello, ").append("World!").getValue();
console.log(result); // "Hello, World!"

✨체이닝 전/후

  • 체이닝 전 코드
builder.append("Hello, ");
builder.append("World!");
builder.getValue();

-체이닝 후 코드

builder.append("Hello, ").append("World!").getValue();

→ 메서드 체이닝으로 작성하면 메서드를 연결해 한 줄로 쓸 수 있음

3.4 접근 제어자, get, set

class Car {
  constructor(color, speed) {
    this.color = color;
    this._speed = speed;
  }

  set speed(value) {
    this._speed = value < 0 ? 0 : value;
  }

  get speed() {
    return this._speed;
  }
}

const car = new Car(200);
car.speed = -100;
car.color = "white";
console.log(car.speed);
console.log(car.color);
  • get set이 꼭 같이 있어야하는 것은 아니긴 함
class Car {
  constructor(color, speed) {
    this.color = color;
    this._speed = speed;
  }

  set speed(value) {
    this._speed = value < 0 ? 0 : value;
  }

  get speed() {
    return this._speed;
  }

  set color(value) {
    this._color= value === "white" ? "black" : value;
  }

  get color() {
    return this._color;
  }
}

const car = new Car(200);
car.speed = -100;
car.color = "white";

console.log(car.speed);
console.log(car.color);

3.5 프라이빗 필드 ->

class Counter {
  #count = 0;
  constructor(count) {
    this.#count = count;
  }

  increment() {
    this.#count++;
  }

  decrement() {
    this.#count--;
  }

  getCount() {
    return this.#count;
  }
}

const count = new Counter(0);
count.count = 200;

count.increment();
count.decrement();

console.log(count.getCount());

연습문제 9. 클래스의 인스턴스 수 추적

Book 클래스를 정의하고, 생성될 때마다 인스턴스 수를 카운트하도록 하세요.

class Book {
  static count = 0; // static으로 선언: 클래스 자체에서 관리하는 변수

  constructor(title) {
    this.title = title;
    Book.count++;
  }

  static getCount() {
    return this.count; // static 메서드에서는 this로 접근할 수 있음
  }
}

// 테스트 케이스
const book1 = new Book("1984");
const book2 = new Book("하이퍼리얼리티");
console.log(Book.getCount()); // 2
  • count가 static으로 선언되었기 때문에 인스턴스가 아닌 클래스에 속해 있음

오버라이딩

  • 자식 클래스가 자신의 부모 클래스들 중 하나에 의해 이미 제공된 함수 등을 특정한 형태로 구현하는 것
  • 부모 클래스에서 이미 정의된 함수 등을 자식 클래스에서 같은 이름으로 사용하되 안에 들어가는 내용(기능, 속성 등)을 바꿔서 사용
  • 자식 클래스도 상속 받은 부모 클래스의 기능들을 어떻게 바꿔서 사용하는지에 따라 그 기능이 달라지게 됨

✨
https://axce.tistory.com/61

0개의 댓글