JavaScript는 프로토타입 기반 언어이며, 프로토타입(Prototype)은 원형 객체를 의미한다.
프로토타입은 객체의 특성을 다른 객체로 상속하는 것을 가능하게 하는 메커니즘이다.
아래 예시로 살펴보자.
class Human {
constructor(name, age) {
this.name = name;
this.age = age;
}
sleep() {
console.log(`${this.name}은 잠에 들었습니다`);
}
}
let kimcoding = new Human('김코딩', 30);
Human.prototype.constructor === Human; // true
Human.prototype === kimcoding.__proto__; // true
Human.prototype.sleep === kimcoding.sleep; // true
prototype
은 Human 클래스의 인스턴스인 kimcoding의 __proto__
이다.prototype
에 있으며, Human 클래스의 인스턴스인 kimcoding에서 kimcoding.sleep으로 사용할 수 있다.Array(배열) 클래스와 인스턴스, 프로토타입의 관계 또한 위의 그림과 원리가 동일하다.
배열(arr)은 Array 클래스의 인스턴스이며, 프로토타입에는 다양한 메서드가 존재한다.
extends
와 super
키워드를 이용해서 상속을 구현할 수 있다.__proto__
를 이용하면 부모 클래스의 프로토타입, 혹은 '부모의 부모 클래스'의 프로토타입을 탐색할 수 있다.아래 mdn 링크에서 클래스 상속을 구현하는 법을 이해하고 연습해보자.
아래와 같이 Person class가 정의되어 있을 때,
class Person {
constructor(first, last, age, gender, interests) {
this.name = {
first,
last
};
this.age = age;
this.gender = gender;
this.interests = interests;
}
greeting() {
console.log(`Hi! I'm ${this.name.first}`);
};
farewell() {
console.log(`${this.name.first} has left the building. Bye for now!`);
};
}
new
키워드로 Person
의 인스턴스를 생성할 수 있다.
let han = new Person('Han', 'Solo', 25, 'male', ['Smuggling']);
han.greeting(); // Hi! I'm Han
let leia = new Person('Leia', 'Organa', 19, 'female' ['Government']);
leia.farewell(); // Leia has left the building. Bye for now
Person
클래스 →(상속) Teacher
클래스 생성: 하위 클래스 생성
하위 클래스를 생성하기 위해 자바스크립트에서는 extends
키워드를 통해 상속 받을 클래스를 명시한다.
(Person
의 first, last, age, gender, interests는 상속, subject, grade는 Teacher
에 새로 추가)
class Teacher extends Person {
constructor(first, last, age, gender, interests, subject, grade) {
this.name = {
first,
last
};
this.age = age;
this.gender = gender;
this.interests = interests;
// subject와 grade는 Teacher 클래스에 새로 추가(Teacher 클래스 전용 속성)
this.subject = subject;
this.grade = grade;
}
}
super
키워드를 사용하면 상위 클래스의 생성자를 호출하며, 매개변수를 통해 상위 클래스의 멤버를 상속받을 수 있다.
class Teacher extends Person {
constructor(first, last, age, gender, interests, subject, grade) {
// super 키워드를 사용하여 코드를 간결하게 줄일 수 있다.
super(first, last, age, gender, interests);
// subject와 grade는 Teacher 클래스에 새로 추가(Teacher 클래스 전용 속성)
this.subject = subject;
this.grade = grade;
}
}
Teacher
의 인스턴스를 생성하면 의도한대로 Teacher
와 Person
양 쪽의 메소드와 속성을 사용할 수 있다.
let snape = new Teacher('Severus', 'Snape', 58, 'male', ['Potions'], 'Dark arts', 5);
snape.greeting(); // Hi! I'm Severus.
snape.farewell(); // Severus has left the building. Bye for now.
snape.age // 58
snape.subject; // Dark arts