클래스

2025. 6. 2. 15:34Coding Study/Javascript

 

1. 클래스

 ES6 에서 도입된 문법

 기존의 프로토타입 기반 상속을 더 쉽고 직관적으로 사용할 수 있게 해줌

 객체 지향 프로그래밍에서 사용하는 설계도 역활

 

2. 클래스의 기본 구조

 constructor 는 인스턴스 생성 시 호출되는 함수

 메서드도 클래스 내부에서 정의할 수 있다.

class Car {
  brand;
  model;
  year;
  mileage;

  constructor(brand, model, year, mileage) {
    this.brand = brand;
    this.model = model;
    this.year = year;
    this.mileage = mileage;
  }

  drive(km) {
    this.mileage += km;
    return `${km}km 주행 완료! 총 주행거리: ${this.mileage}km`;
  }

  info() {
    return `${this.year}년식 ${this.brand} ${this.model}, 주행거리: ${this.mileage}km`;
  }
}

 

 

// 자동차 객체 생성
const myCar = new Car("현대", "아반떼", 2022, 15000);

console.log(myCar); 
// Car { brand: '현대', model: '아반떼', year: 2022, mileage: 15000 }

console.log(myCar.info()); 
// 2022년식 현대 아반떼, 주행거리: 15000km

console.log(myCar.drive(500)); 
// 500km 주행 완료! 총 주행거리: 15500km

console.log(myCar.info()); 
// 2022년식 현대 아반떼, 주행거리: 15500km

 

 

클래스 안에 프로퍼티를 별도로 선언하지 않아도 constructir 의 this.프로퍼티명=값 형태로 할당하면 해당 프로퍼티가 자동으로 객체에 추가 된다.

 

권장되지는 않는다.

class Car {
  // 여기서 brand, model, year, mileage를 따로 선언하지 않습니다.

  constructor(brand, model, year, mileage) {
    this.brand = brand;
    this.model = model;
    this.year = year;
    this.mileage = mileage;
  }

  info() {
    return `${this.year}년식 ${this.brand} ${this.model}, 주행거리: ${this.mileage}km`;
  }
}

const myCar = new Car("기아", "K5", 2021, 12000);

console.log(myCar); 
// Car { brand: '기아', model: 'K5', year: 2021, mileage: 12000 }

console.log(myCar.info()); 
// 2021년식 기아 K5, 주행거리: 12000km

 

 

 

3. 상속

 1) 속성을 그대로 물려받고 매서드만 추가 할 경우

   - extends 를 사용하여 이름을 정의 하고 추가할 메서드만 작성을 한다.

   - 그리고 정의된 이름으로 인스턴스를 생성한다.

   - 부모 클래스에서는 자식 클래스에서 생성한 매서드 호출은 불가능 하다.

class Vehicle {
    brand;
    model;

  constructor(brand, model) {
    this.brand = brand;
    this.model = model;
  }

  drive() {
    console.log(`${this.brand} ${this.model}가(이) 주행을 시작합니다.`);
  }
}

// 자식 클래스: Car (Vehicle의 속성/메서드 상속 + horn 메서드 추가)
class Car extends Vehicle {
  horn() {
    console.log(`${this.brand} ${this.model}가(이) 빵빵! 경적을 울립니다.`);
  }
}

const myCar = new Car("기아", "K7");

console.log(myCar.brand); // 기아
console.log(myCar.model); // K7

myCar.drive(); // 기아 K7가(이) 주행을 시작합니다.
myCar.horn();  // 기아 K7가(이) 빵빵! 경적을 울립니다.

 

 

 

 2) 속성 추가 + 매서드 추가 하는 경우 

   super 키워드 사용 하여 기존 속성을 받아온다. 

   기존 속성에 전기차의 속성(배터리용량, 충전)을 추가 하고 싶을때 extends 를 사용 하여 기존 부모 속성을 물려받아

   추가 할 수 있다.

class Car {
    brand;
    model;

  constructor(brand, model) {
    this.brand = brand;
    this.model = model;
  }

  drive() {
    console.log(`${this.brand} ${this.model}가(이) 주행을 시작합니다.`);
  }
}

class ElectricCar extends Car {
  constructor(brand, model, battery) {
    super(brand, model); // 부모 클래스의 생성자 호출
    this.battery = battery;
  }

  charge() {
    console.log(`${this.brand} ${this.model}의 배터리를 충전합니다.`);
  }
}

const tesla = new ElectricCar("테슬라", "모델3", 75);
tesla.drive(); // 테슬라 모델3가(이) 주행을 시작합니다.
tesla.charge(); // 테슬라 모델3의 배터리를 충전합니다.

 

4. Static 키워드

   static 키워드로 선언하면 인스턴스에서는 접근이 불가능 하고 클래스 에서만 접근이 가능하다.

class Car {
    brand;
    model;

  static totalCars = 0; // static 필드: 전체 자동차 개수

  constructor(brand, model) {
    this.brand = brand;
    this.model = model;
    Car.totalCars++; // 새 인스턴스가 만들어질 때마다 static 필드 증가
  }

  drive() {
    console.log(`${this.brand} ${this.model}가(이) 주행을 시작합니다.`);
  }

  static getTotalCars() { // static 메서드: 전체 자동차 개수 반환
    return Car.totalCars;
  }
}

const car1 = new Car("현대", "아반떼");
const car2 = new Car("기아", "K5");

console.log(car1.brand); // 현대
console.log(car2.model); // K5

console.log(Car.getTotalCars()); // 2 (static 메서드는 클래스명으로 호출)
console.log(car1.getTotalCars); // undefined (인스턴스에서는 static 메서드 호출 불가)
console.log(car1.totalCars); // undefined (static 필드는 인스턴스에서 접근 불가)
console.log(Car.totalCars); // 2 (클래스명으로 접근)

 

 

5. Private 필드 및 getter & Setter

  number는 private 필드이므로 클래스 외부에서 직접 접근이 불가능 하다.

  carNumber라는 getter를 통해서만 차량번호를 읽을 수 있다.

  setter는 set carNumber(newNumber)와 같이 정의한다.

  값을 변경할 때는 myCar.carNumber = "새로운값"처럼 대입 연산자를 사용 한다.

  하지만 private 변수의 경우에는 setter 를 안쓰는 것을 추천한다.

class Car {
  #number;     // 차량번호(외부에서 직접 접근 불가)
  brand;
  model;
  
  constructor(number, brand, model) {
    this.#number = number;
    this.brand = brand;
    this.model = model;
  }

  // 차량번호를 읽는 getter
  get carNumber() {
    return this.#number;
  }

  // 차량번호를 바꾸는 setter (잘 사용하진 않음)
  set carNumber(newNumber) {
    this.#number = newNumber;
  }
}

const myCar = new Car("12가3456", "현대", "그랜저");

console.log(myCar.carNumber); // 12가3456
console.log(myCar); // Car { brand: '현대', model: '그랜저' }

// 외부에서 #number에 직접 접근 시도
console.log(myCar.#number); // SyntaxError: Private field '#number' must be declared in an enclosing class

// setter를 사용해서 차량번호 변경
myCar.carNumber = "34나5678";

console.log(myCar.carNumber); // 34나5678

 

 

'Coding Study > Javascript' 카테고리의 다른 글

배열  (0) 2025.08.29
prototype  (0) 2025.05.24
콜백 함수  (0) 2025.05.10
실행 컨택스트  (0) 2025.04.23
자바스크립트 var, let, const 키워드  (0) 2025.04.18