7.1 상속의 기본
JavaScript의 클래스 상속은 기존 클래스의 기능을 재사용하고 확장하면서 새로운 클래스를 생성할 수 있게 해줘. 이건 객체 지향 프로그래밍(OOP)의 핵심이야, 객체의 행동을 관리하고 클래스의 계층 구조를 만들 수 있도록 도와주거든.
클래스 상속을 위해 extends
키워드를 사용하는데, 다른 클래스를 상속받는 클래스를 파생 클래스(subclass)라고 하고, 상속의 기반이 되는 클래스를 기본 클래스(superclass)라고 해.
예시:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Rex');
dog.speak(); // "Rex barks."
설명:
Animal
클래스는 생성자와speak()
메서드를 가진 기본 클래스야.Dog
클래스는Animal
을 상속하고speak()
메서드를 재정의해.Dog
클래스의 인스턴스dog
는 재정의된speak()
메서드를 사용해.
7.2 super 키워드
super
키워드는 파생 클래스에서 기본 클래스의 생성자나 메서드를 호출하는 데 사용돼.
1. 기본 클래스의 생성자 호출
파생 클래스는 this
를 사용하기 전에 super()
를 사용해서 기본 클래스의 생성자를 호출해야 해.
예시:
Dog
생성자는 super(name)
을 호출해서 기본 클래스 Animal
의 name 속성을 초기화해.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Rex', 'Labrador');
console.log(dog.name); // "Rex"
console.log(dog.breed); // "Labrador"
dog.speak(); // "Rex barks."
2. 기본 클래스의 메서드 호출
기본 클래스의 메서드는 파생 클래스에서 super
를 사용해서 호출할 수 있어.
예시:
Dog
클래스의 speak()
메서드는 super.speak()
를 사용해서 기본 클래스 Animal
의 speak()
메서드를 호출하고, 그 다음에 자신의 로직을 수행해.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
super.speak(); // 기본 클래스 메서드 호출
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Rex');
dog.speak();
// "Rex makes a noise."
// "Rex barks."
7.3 상속과 메서드 재정의
상속은 파생 클래스가 기본 클래스의 메서드를 재정의할 수 있게 해. 이로 인해 메서드의 기능을 변경하거나 확장할 수 있는거지.
예시:
Dog
클래스의 speak()
메서드는 기본 클래스 Animal
의 speak()
메서드를 재정의해서 자신만의 구현을 제공해.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const animal = new Animal('Generic Animal');
animal.speak(); // "Generic Animal makes a noise."
const dog = new Dog('Rex');
dog.speak(); // "Rex barks."
7.4 상속과 추가 메서드
파생 클래스는 기본 클래스에 없는 새로운 메서드를 추가할 수 있어.
예시:
Dog
클래스는 기본 클래스 Animal
에 없는 새로운 메서드 fetch()
를 추가해.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
fetch() {
console.log(`${this.name} is fetching.`);
}
}
const dog = new Dog('Rex');
dog.speak(); // "Rex barks."
dog.fetch(); // "Rex is fetching."
7.5 상속 확인
상속을 확인하려면 instanceof
연산자와 isPrototypeOf()
메서드를 사용할 수 있어.
예시:
instanceof
연산자는 객체가 클래스의 인스턴스인지 확인해줘. isPrototypeOf()
메서드는 객체의 프로토타입이 다른 객체의 프로토타입 체인의 일부인지 확인해줘.
console.log(dog instanceof Dog); // true
console.log(dog instanceof Animal); // true
console.log(Animal.prototype.isPrototypeOf(Dog.prototype)); // true
GO TO FULL VERSION