728x90

✅ 1. 클래스 기본 문법
자바스크립트에서 class는 객체를 생성하기 위한 템플릿으로, ES6(2015)부터 도입된 문법으로 자바나 C#과 조금 비슷한 구조입니다. 클래스 선언 시 class를 사용합니다.
class Person {
// 생성자 (객체 생성 시 자동 실행)
constructor(name, age) {
this.name = name;
this.age = age;
}
// 메서드 (Prototype에 저장)
sayHell() {
console.log(`Hello, my name is ${this.name}, ${this.age} years old`);
}
}
// 객체 생성
const p1 = new Person("James", 25);
p1.sayHell(); // Hello, my name is James, 25 years old
✅ 2. constructor
constructor은 클래스에서 객체가 생성될 때 자동으로 실행되는 메서드이며 주로 프로퍼티 초기화 시 사용합니다.
class Animal {
constructor(type) {
this.type = type;
}
}
const a = new Animal("Lion");
console.log(a.type); // Lion
✅ 3. extends (상속)
extends(상속)은 한 클래스가 다른 클래스를 상속받을 때 사용되며, 부모 클래스의 기능을 자식 클래스가 물려받습니다.
class Juice {
constructor(name) {
this.name = name;
}
eat() {
console.log(`${this.name}를 선택`);
}
}
class Coke extends Juice {
zero() {
console.log(`${this.name}을 마신다`);
}
}
const human = new Coke("제로콜라");
human.eat(); // 제로콜라를 선택
human.zero(); // 제로콜라를 마신다
✅ 4. super
super는 자식 클래스에서 부모 클래스의 생성자(constructor)나 메서드를 호출할때 사용되며, extends와 같이 써야합니다.
class Background {
constructor(name) {
this.name = name;
}
info() {
console.log(`색상: ${this.name}`);
}
}
class Black extends Background {
constructor(name, color) {
super(name); // 부모 클래스 constructor 호출
this.color = color;
}
info() {
super.info(); // 부모의 info 메서드 호출
console.log(`색상코드: ${this.color}`);
}
}
const c = new Black("검정색", "#000");
c.info();
// 색상: 검정색
// 색상코드: #000
✅ 정리
- class -> 객체 템플릿 선언
- constructor -> 객체 초기화 메서드
- extends -> 상속
- super -> 부모 클래스 constructor 메서드 호출
GitHub - javascript-only/newJSRoom: https://thinky.tistory.com/category/Front-End/JavaScript
https://thinky.tistory.com/category/Front-End/JavaScript - javascript-only/newJSRoom
github.com
728x90
LIST
'Front-End > JavaScript' 카테고리의 다른 글
| [Javascript] New Javascript 11장 프라이빗 필드/메서드 (0) | 2025.09.10 |
|---|---|
| [Javascript] New Javascript 10장 모듈 시스템 (0) | 2025.09.08 |
| [Javascript] New Javascript 8장 async/await (0) | 2025.08.30 |
| [Javascript] New Javascript 7장 Null 병합 연산자 (2) | 2025.08.27 |
| [Javascript] New Javascript 6장 - 옵셔널 체이닝 (1) | 2025.08.25 |