1️⃣ 상속 (Inheritance)
2️⃣ super
3️⃣ proto, Object.create, Object.assign
5️⃣ Prototype과 proto, 그리고 프로토타입 체인(Prototype Chain)
상속 (Interitance)
class에서의 상속
class Person { // 메인 클래스
constructor(name, first, second){
this.name = name;
this.first = first;
this.second = second;
}
sum(){
return 'prototype : '+(this.first+this.second);
}
}
class PersonPlus extends Person { // 메인 클래스인 Person에 상속된 서브 클래스
avg() {
return (this.first+this.second)/2;
}
}
let kim = new PersonPlus('kim', 10, 20);
console.log('kim.sum()', kim.sum()); // kim.sum() prototype : 30
console.log('kim.avg()', kim.avg()); // kim.avg() 15
클래스에서의 상속은 생성한 클래스의 이름 뒤에 extends
와 함께 메인이 될 클래스명을 붙이는 것으로 상속을 적용할 수 있다.
PersonPlus
내에 변화가 이루어질 경우, PersonPlus
를 통해 생성된 객체에는 영향이 적용되지만 메인 클래스인 Person
을 통해 생성된 객체에는 영향을 주지 않는다.
PersonPlus
의 내용이 기존 Person
에서 확장된 내용을 담고 있으므로, 확장된 내용을 담지 않은 기존 객체인 Person
은 영향을 받지 않는다.Person
내에 변화가 생기면, PersonPlus
는 Person
에서 확장된 내용이므로 그 변화의 영향을 같이 받는다.생성자 함수에서의 상속
function Person(name, first, second){
this.name = name;
this.first = first;
this.second = second;
}
Person.prototype.sum = function(){
return this.first + this.second;
}
function PersonPlus(name, first, second, third){
Person.call(this, name, first, second);
this.third = third;
}
PersonPlus.prototype.avg = function(){
return (this.first+this.second+this.thrid)/3;
}
생성자 함수에서의 상속은 **call()
메소드를 이용해 상속/확장을 적용할 수 있다.**
PersonPlus
에 함수 Person
을 상속시키려면 PersonPlus
코드 내에서 call()
을 이용하면 된다.
call()
의 첫 번째 인자값은 this
로 받고자 하는 데이터였으므로, 여기서는 this를 인자로 넣는다.
this
는 생성자 함수 PersonPlus
를 가리키는 this
이다.super
와 매우 유사하다.단, call()
을 이용해 상속할 수는 있지만 외부에서 prototype
으로 정의한 속성이나 메소드를 받아오지는 못한다.
메인 생성자 함수의 prototype
까지 상속받으려면 서브 생성자 함수의 prototype
속성값을 메인 생성자 함수의 prototype
객체로 하는 새로운 객체를 만들면 된다.
function Person(name, first, second){
this.name = name;
this.first = first;
this.second = second;
}
Person.prototype.sum = function(){
return this.first + this.second;
}
function PersonPlus(name, first, second, third){
Person.call(this, name, first, second);
this.third = third;
}
PersonPlus.prototype.avg = function(){
return (this.first+this.second+this.thrid)/3;
}
**PersonPlus.prototype = Object.create(Person.prototype);**
PersonPlus
의 prototype
값을 메인 생성자 함수 Person
의 prototype
객체를 본뜬 새로운 객체로 지정함으로서 상속받을 수 있게 됐다.그러나 이 방식을 사용하게 되면 서브 생성자 함수 PersonPlus
를 이용해 생성한 새로운 객체에 생성자(constructor
)를 확인 시, PersonPlus
가 아닌 메인 생성자 함수 Person
을 가리키게 된다.
이를 방지하기 위해, PersonPlus
의 prototype
속성에 있는 생성자(constructor
) 속성을 자신으로 받도록 지정해줘야 한다.
즉, 서브 생성자 함수의 prototype
객체의 constructor
속성값을 자신으로 지정해줘야 한다.
**PersonPlus.prototype.constructor = PersonPlus;**
PersonPlus
가 참조하는 prototype
객체는 현재 자신이 아닌 Object.create
를 통해 메인 생성자 함수인 Person
의 prototype
을 본뜬 객체이므로, 해당 객체가 가진 생성자는 기존에 참조하고 있던 Person을 받아오고 있을 것이다.
그렇기 때문에 이런 식으로 서브 생성자 함수인 PersonPlus
가 현재 prototype
객체의 생성자임을 가리키도록 지정해줘야 한다.