클래스 기반 상속
클래스 기반 상속은 주로 부모 클래스의 프라이빗 속성을 자식 클래스에 전달하는 방식이다. 이때
call을 사용해 자식 클래스의
this를 부모 클래스로 변경한다.
function Human(name, age) {
this.name = name;
this.age = age;
}
function Developer(name, age, role) {
Human.call(this, name, age);
this.role = role;
}
const person = new Human('아이언맨', 40);
const dev = new Developer('토니스타크', 40, '엔지니어');
복사 상속
복사 상속은 부모 객체의 속성과 메서드를 자식 객체로 직접 복사하는 방식이다. 일반적으로
for...in을 통해 부모 객체의 메서드를 순회하며 자식 객체의 프로토타입에 할당한다.
function Animal(type) {
this.type = type;
}
Animal.prototype.walk = function() {
console.log('걷는다');
};
function Dog(name) {
Animal.call(this, '강아지');
this.name = name;
}
for (let key in Animal.prototype) {
if (Animal.prototype.hasOwnProperty(key)) {
Dog.prototype[key] = Animal.prototype[key];
}
}
Dog.prototype.bark = function() {
console.log('멍멍!');
};
const myDog = new Dog('루피');
myDog.walk();
myDog.bark();
Object.assign() 활용한 복사
Object.assign()는 객체 간 속성 복사를 쉽게 처리할 수 있다. 이를 통해 깊은 복사나 얕은 복사를 구현할 수 있다.
function Car(model) {
this.model = model;
}
Car.prototype.drive = function() {
console.log('주행 중');
};
function SportsCar(model, speed) {
Car.call(this, model);
this.speed = speed;
}
Object.assign(SportsCar.prototype, Car.prototype);
SportsCar.prototype.race = function() {
console.log('레이싱 모드');
};
const car = new SportsCar('Ferrari', 300);
car.drive();
car.race();
프로토타입 기반 상속
프로토타입 상속은 부모 클래스의 프로퍼티와 메서드를 자식 클래스가 공유하도록 하는 방식이다.
function Parent(name) {
this.name = name;
}
Parent.prototype.greet = function() {
console.log(`안녕하세요, ${this.name}`);
};
function Child(name) {
Parent.call(this, name);
}
function Temp() {}
Temp.prototype = Parent.prototype;
Child.prototype = new Temp();
const child = new Child('자식');
child.greet();
기생 조합형 상속
기생 조합형 상속은 자식 클래스가 부모 클래스의 프라이빗 및 공용 속성을 모두 상속받는 방식이다.
function Base(name) {
this.name = name;
}
Base.prototype.introduce = function() {
console.log(`저는 ${this.name}입니다.`);
};
function Derived(name, job) {
Base.call(this, name);
this.job = job;
}
Derived.prototype = Object.create(Base.prototype);
Derived.prototype.constructor = Derived;
Derived.prototype.work = function() {
console.log(`${this.job}으로 일합니다.`);
};
const derived = new Derived('홍길동', '개발자');
derived.introduce();
derived.work();
ES6 클래스 상속
ES6에서는 클래스 문법을 제공하여 더 간결하게 상속을 구현할 수 있다.
extends 키워드와 함께 부모 클래스를 상속하고, 자식 클래스에서
super를 통해 부모 클래스의 생성자를 호출할 수 있다.
class Figure {
constructor(width, height) {
this.width = width;
this.height = height;
}
getArea() {
return this.width * this.height;
}
}
class Rectangle extends Figure {
constructor(width, height, color) {
super(width, height);
this.color = color;
}
getColor() {
return this.color;
}
}
const rect = new Rectangle(10, 5, '빨간색');
console.log(rect.getArea()); // 50
console.log(rect.getColor()); // 빨간색