6.1 클래스 생성자
클래스의 생성자와 메서드는 JavaScript에서 객체 지향 프로그래밍의 기본 요소야. 이들은 객체를 생성하고 초기화할 수 있게 해주며, 객체의 동작을 정의할 수 있어. 아래에서 생성자와 클래스 메서드가 어떻게 작동하는지, 그리고 이들을 어떻게 사용하는지 살펴보자.
생성자가 뭐야?
생성자는 클래스의 특별한 메서드로, 새로운 클래스 인스턴스를 만들 때 호출돼. 객체를 초기화하고, 그 속성값을 설정하고, 다른 초기 작업을 수행하는 데 사용돼.
생성자 정의
생성자는 constructor
키워드를 사용해 정의해. 생성자 안에서는 this
키워드를 통해 객체의 속성과 메서드에 접근할 수 있어.
구문:
class ClassName {
constructor(파라미터) {
// 객체 초기화
}
}
예시:
Person
클래스에서 constructor
메서드는 두 개의 파라미터를 받아: name
그리고 age
.
이 파라미터들은 생성된 객체의 name
과 age
속성을 초기화하는데 사용돼.
JavaScript
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const person1 = new Person('Alice', 30);
const person2 = new Person('Bob', 25);
console.log(person1.name); // 출력: Alice
console.log(person2.age); // 출력: 25
기본 생성자
생성자가 명시적으로 정의되지 않은 경우, JavaScript는 자동으로 빈 기본 생성자를 만들어.
예시:
JavaScript
class Animal {}
const animal = new Animal();
console.log(animal); // Animal 클래스의 내용 출력 {}
4.2 클래스 메서드
클래스 메서드는 클래스 본문 내에 정의되며, 이 클래스에 의해 생성된 객체에 기능을 제공해. 메서드는 자동으로 클래스 프로토타입에 추가되어, 모든 클래스 인스턴스가 이들을 상속하고 사용할 수 있게 해줘.
구문:
class ClassName {
constructor(파라미터) { // 객체 초기화 }
메서드1() { // 메서드 본문 }
메서드2() { // 메서드 본문 }
}
예시:
JavaScript
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
this.mileage = 0;
}
drive(distance) {
this.mileage += distance;
console.log(`${this.brand} ${this.model} drove ${distance} miles. Total mileage: ${this.mileage}`);
}
getDetails() {
return `${this.brand} ${this.model}, Mileage: ${this.mileage}`;
}
}
const myCar = new Car('Toyota', 'Camry');
myCar.drive(50); // "Toyota Camry drove 50 miles. Total mileage: 50"
console.log(myCar.getDetails()); // "Toyota Camry, Mileage: 50"
설명:
Car
클래스에는 두 개의 메서드가 정의되어 있어:drive()
과getDetails()
drive()
메서드는 자동차의 주행거리를 증가시키고, 주행한 거리에 대한 정보를 출력해getDetails()
메서드는 자동차에 대한 정보를 포함한 문자열을 반환해
6.3 프라이빗 메서드
새로운 ECMAScript 사양의 도입으로 클래스 외부에서 접근할 수 없는 프라이빗 메서드와 속성을 만들 수 있는 기능이 생겼어. 이를 위해 # 기호를 이름의 일부로 사용해.
프라이빗 메서드와 속성의 예:
JavaScript
class BankAccount {
#balance = 0;
constructor(initialBalance) {
this.#balance = initialBalance;
}
#validateAmount(amount) {
if (amount <= 0) {
throw new Error('Amount must be positive.');
}
}
deposit(amount) {
this.#validateAmount(amount);
this.#balance += amount;
console.log(`Deposited ${amount}. New balance: ${this.#balance}`);
}
withdraw(amount) {
this.#validateAmount(amount);
if (amount > this.#balance) {
throw new Error('Insufficient funds.');
}
this.#balance -= amount;
console.log(`Withdrew ${amount}. New balance: ${this.#balance}`);
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount(100);
account.deposit(50); // 출력: Deposited 50. New balance: 150
account.withdraw(30); // 출력: Withdrew 30. New balance: 120
console.log(account.getBalance()); // 출력: 120
// 프라이빗 메서드나 속성에 접근하려고 하면 에러가 발생해
account.#balance; // SyntaxError
account.#validateAmount(50); // SyntaxError
GO TO FULL VERSION