상속(Inheritance)는 객체 지향 프로그래밍에서 중요한 개념 중 하나로, 코드의 재사용성을 높이고 객체간의 계층 구조를 만들어내는 매커니즘이다.
즉, 상속은 기존 클래스 또는 객체(부모 또는 상위 클래스 / 객체)에서 속성과 메서드를 파생된 새로운 클래스 또는 객체 (자식 또는 하위 클래스 / 객체)에게 공유하거나 전달하는 과정을 의미한다. 이로써 코드의 중복을 최소화하고, 유지보수성을 향상 시킬 수 있다.
자바스크립트에서는 프로토타입을 이용하여 상속을 구현한다. 객체는 생성될 때 '프로토타입 (prototype)'이라는 특수한 속성을 지니게 되는데, 이 프로토타입에는 해당 객체를 생성하는데 사용된 생성자 함수의 프로토타입 객체가 할당된다. 이로 인해 객체는 해당 프로토타입 객체의 속성과 메서드를 상속받는다.
// 부모 클래스
function Animal(name) {
this.name = name;
}
// 부모 클래스의 메서드
Animal.prototype.sayHello = function() {
console.log(`안녕하세요, 저는 ${this.name}입니다.`);
};
// 자식 클래스
function Dog(name, breed) {
// 부모 클래스 생성자 호출
Animal.call(this, name);
this.breed = breed;
}
// 자식 클래스의 인스턴스 생성
var myDog = new Dog('멍멍이', '진돗개');
// 자식 클래스는 부모 클래스의 메서드를 상속받음
myDog.sayHello(); // 출력: 안녕하세요, 저는 멍멍이입니다.
Dog 클래스는 Animal 클래스를 상속받는다. Dog 클래스의 인스턴스 myDog은 Animal 클래스의 sayHello 메서드를 호출 할 수 있다.
이러한 상속 메커니즘을 통해 코드의 재사용성이 높아지며, 관련된 객체간의 계층 구조를 형성할 수 있다.
// 부모 클래스
function Animal(name) {
this.name = name;
}
// 부모 클래스의 메서드
Animal.prototype.sayHello = function() {
console.log(`안녕하세요, 저는 ${this.name}입니다.`);
};
// 자식 클래스
function Dog(name, breed) {
// 부모 클래스 생성자 호출
Animal.call(this, name);
this.breed = breed;
}
// 자식 클래스의 프로토타입을 부모 클래스의 인스턴스로 설정
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
// 자식 클래스의 메서드
Dog.prototype.bark = function() {
console.log('멍멍!');
};
// 자식 클래스의 인스턴스 생성
var myDog = new Dog('멍멍이', '진돗개');
// 자식 클래스는 부모 클래스의 메서드를 상속받음
myDog.sayHello(); // 출력: 안녕하세요, 저는 멍멍이입니다.
myDog.bark(); // 출력: 멍멍!
// ES6 클래스 문법
class Animal {
constructor(name) {
this.name = name;
}
sayHello() {
console.log(`안녕하세요, 저는 ${this.name}입니다.`);
}
}
// 상속
class Dog extends Animal {
constructor(name, breed) {
// 부모 클래스 생성자 호출
super(name);
this.breed = breed;
}
bark() {
console.log('멍멍!');
}
}
// 인스턴스 생성
var myDog = new Dog('멍멍이', '진돗개');
myDog.sayHello(); // 출력: 안녕하세요, 저는 멍멍이입니다.
myDog.bark(); // 출력: 멍멍!
extends 키워드를 사용하여 상속을 선언하고, super 키워드를 통해 부모 클래스의 생성자를 호출할 수 있다.