인스턴스 생성하기
Coddy JavaScript 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨 — 56개 중 12번째.
클래스를 정의한 후, new 키워드를 사용하여 해당 클래스를 기반으로 객체를 생성할 수 있습니다. 이러한 객체들을 인스턴스라고 부릅니다.
간단한 Person 클래스가 있다고 가정해 봅시다:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name}`;
}
}Person 클래스의 인스턴스를 생성합니다:
const john = new Person("John", 30);위의 코드를 실행한 후, john은 다음과 같은 Person 클래스의 인스턴스입니다:
name속성이 "John"으로 설정됨age속성이 30으로 설정됨
인스턴스의 속성과 메서드에 접근할 수 있습니다:
console.log(john.name); // 출력: John
console.log(john.greet()); // 출력: Hello, my name is John동일한 클래스에서 여러 인스턴스를 생성할 수 있습니다:
const sarah = new Person("Sarah", 25);
console.log(sarah.name); // 출력: Sarah챌린지
Student 클래스가 주어집니다. 여러분의 작업은 driver.js 파일에 두 개의 학생 인스턴스를 생성하는 것입니다:
- 이름이 "Sarah"이고 점수가 85인
student1을 생성하세요 - 이름이 "Mike"이고 점수가 92인
student2를 생성하세요
치트 시트
클래스의 인스턴스를 생성하려면 new 키워드를 사용하세요:
const john = new Person("John", 30);점 표기법을 사용하여 인스턴스의 속성과 메서드에 접근합니다:
console.log(john.name); // 출력: John
console.log(john.greet()); // 출력: Hello, my name is John동일한 클래스에서 여러 인스턴스를 생성할 수 있습니다:
const sarah = new Person("Sarah", 25);
console.log(sarah.name); // 출력: Sarah직접 해보기
import { Student } from './student.js';
// TODO: 이름이 "Sarah"이고 점수가 85인 student1이라는 이름의 Student 클래스 인스턴스를 생성하세요.
// TODO: 이름이 "Mike"이고 점수가 92인 student2라는 이름의 Student 클래스 인스턴스를 생성하세요.
// 테스트 코드 - 수정하지 마세요
console.log(student1.name); // "Sarah"가 출력되어야 합니다
console.log(student2.grade); // 92가 출력되어야 합니다이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.