프로퍼티와 메서드
Coddy JavaScript 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨 — 56개 중 13번째.
JavaScript의 클래스를 사용하면 클래스의 모든 인스턴스가 공유할 속성과 메서드를 정의할 수 있습니다.
속성을 가진 클래스를 생성합니다:
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
}인스턴스를 생성할 때, 생성자(constructor)는 다음 속성들을 설정합니다:
const myCar = new Car('Toyota', 'Corolla');
console.log(myCar.make); // 출력: 'Toyota'
console.log(myCar.model); // 출력: 'Corolla'클래스에 메서드를 추가합니다:
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
getDescription() {
return `This car is a ${this.make} ${this.model}.`;
}
}이제 모든 인스턴스에서 이 메서드를 호출할 수 있습니다:
const myCar = new Car('Toyota', 'Corolla');
console.log(myCar.getDescription()); // 출력: 'This car is a Toyota Corolla.'챌린지
book.js 파일에 다음 내용을 포함하는 Book 클래스를 생성하세요:
title,author,pages매개변수를 받아 이를 속성으로 설정하는 생성자.- “Title: [title], Author: [author], Pages: [pages]” 형식의 문자열을 반환하는
getInfo메서드. class선언 앞에export를 추가하여 클래스를 내보내세요.
치트 시트
JavaScript의 클래스는 모든 인스턴스가 공유하는 속성과 메서드를 정의합니다.
생성자(constructor)를 사용하여 클래스를 생성합니다:
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
}new를 사용하여 인스턴스를 생성합니다:
const myCar = new Car('Toyota', 'Corolla');
console.log(myCar.make); // Output: 'Toyota'클래스에 메서드를 추가합니다:
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
getDescription() {
return `This car is a ${this.make} ${this.model}.`;
}
}인스턴스에서 메서드를 호출합니다:
const myCar = new Car('Toyota', 'Corolla');
console.log(myCar.getDescription()); // Output: 'This car is a Toyota Corolla.'클래스를 내보냅니다(Export):
export class Car {
// class definition
}직접 해보기
import { Book } from './book.js';
// 테스트 (이 부분을 수정하지 마세요)
const book = new Book("JavaScript Basics", "John Doe", 200);
console.log(book.getInfo());
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.