본문 바로가기

프론트엔드/JavaScript

[JavaScript] 클래스

반응형

JavaScript 클래스

 

클래스

  • ES6(ECMAScript 2015)부터 도입된 `class` 키워드를 사용하여 클래스를 정의할 수 있습니다.
  • 클래스를 활용하여 객체 지향 프로그래밍의 개념을 자바스크립트에서 구현할 수 있습니다.

 

클래스 상속

class Rectangle extends Shape {
  constructor(color, width, height) {
    super(color);
    this.width = width;
    this.height = height;
  }

  getArea() {
    return this.width * this.height;
  }
}

const rect1 = new Rectangle("blue", 10, 20);
console.log(rect1.getColor());  // blue
  • `extends` 키워드를 이용해 상속합니다.
  • `super` 키워드는 상속한 클래스의 `constructor`를 호출
  • 생성자는 `constructor` 키워드를 사용하여 정의되며, 클래스의 인스턴스를 초기화하는 데 사용됩니다.

 

오버라이딩(Overriding)

class Shape {
  constructor(color) {
    this.color = color;
  }
  getColor() {
    return `Shape's color is ${this.color}`;
  }
}

const shape1 = new Shape("black");
console.log(shape1.getColor()); 

class Rectangle extends Shape {
  constructor(color, width, height) {
    super(color);
    this.width = width;
    this.height = height;
  }

  getArea() {
    return this.width * this.height;
  }

  getColor() {
    return `Rectangle's color is ${this.color}`;
  }
}

const rect1 = new Rectangle("blue", 10, 20);
console.log(rect1.getColor()); 

  • 부모 클래스 메서드의 기능을 확장할 때 사용합니다.

 

접근자 프로퍼티 (getter와 setter)

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

const car1 = new Car(-100);

-100이 들어가면 안되니까😯 이를 접근자 프로퍼티(accessor property) gettersetter로 제어합니다.

  • getter는 클래스 필드에 접근합니다.
  • setter는 클래스 필드 값을 할당합니다.
class Car {
  constructor(speed) {
    this.speed = speed;
  }

  set speed(value) {
    if (value < 0) {
      throw new Error("⚠️Speed must be positive");
    } else {
      this._speed = value;
    }
  }

  get speed() {
    return this._speed;
  }

  getSpeed() {
    return this.speed;
  }
}

const car1 = new Car(6);
console.log(car1.getSpeed());
const car2 = new Car(-100);
console.log(car2.getSpeed());

 

비공개 속성(Private properties) `#`

const car1 = new Car(6);
car1.speed = 10;
console.log(car1.getSpeed());  // 10

해당 코드는 외부에서 접근 가능하여 값이 바뀌는 문제가 있습니다.

class Car {
  #speed; // private 속성
  constructor(speed) {
    this.#speed = speed;
  }

  set speed(value) {
    if (value < 0) {
      throw new Error("⚠️Speed must be positive");
    } else {
      this._speed = value;
    }
  }

  get speed() {
    return this._speed;
  }

  getSpeed() {
    return this.#speed;
  }
}

const car1 = new Car(6);
car1.speed = 10;
console.log(car1.getSpeed());  // 6
car1.#speed = 10; // Error
  • `#` 키워드를 이용하면 클래스 외부에서 참조가 불가능합니다.

 

정적 메서드

// static
class MathUtils {
  static PI = 3.14;

  constructor() {}

  static add(a, b) {
    return a + b;
  }
}

const mathUtil = new MathUtils();
console.log(MathUtils.PI);
console.log(mathUtil.PI);
console.log(MathUtils.add(10, 20));
console.log(mathUtil.add(1, 2));
  • `static`은 인스턴스화 되지 않습니다. 
  • 정적 메서드는 클래스의 인스턴스가 아닌 클래스 자체에서 호출되는 메서드입니다.
  • 멤버 변수로 선언되지 않습니다. 인스턴스 접근 불가능.
  • static 필드는 해당 클래스에 직접 접근해야만 사용할 수 있습니다.

  • 정적 속성과 메서드는 상속되지 않습니다.

 

인스턴스 생성 방법

프로토타입에서 인스턴스 생성 방법

function Shape(color) {
  this.color = color;
  this.getColor = function () {
    return this.color;
  };
}

const shape1 = new Shape("black");

클래스에서 인스턴스 생성 방법

class Shape {
  constructor(color) {
    this.color = color;
  }
  getColor() {
    return this.color;
  }
}

const shape1 = new Shape("black");
console.log(shape1.getColor());  // black
반응형

'프론트엔드 > JavaScript' 카테고리의 다른 글

[JavaScript] 비동기  (1) 2024.06.04
[JavaScript] 이벤트 리스너  (0) 2024.06.04