상속(Inheritance)이란?
- 특정 개체의 로직을 그대로 물려받는 또 다른 객체를 만들수 있는 기능
- 단순히 물려받는 것은 의미가 없기 때문에
기존의 로직을 수정해서 파생된 새로운 객체를 만들 수 있게 해준다.
- 단순히 물려받는 것은 의미가 없기 때문에
//기본적인 함수 코드
function Student(grade, classNo){
this.grade = grade;
this.classNo = classNo;
this.info = function(){
console.log('grade : ' + this.grade + ' class : ' + this.classNo)
};
}
var s = new Student(3, 11);
s.info();
//상속을 위한 코드 변경
function Student(grade, classNo){
this.grade = grade;
this.classNo = classNo;
}
Student.prototype.grade = null; //protype 초기화
Student.prototype.classNo = null; //protype 초기화
Student.prototype.info = function(){
console.log('grade : ' + this.grade + ' class : ' + this.classNo)
}; //protype 초기화
var s = new Student(3, 11);
s.info();
//상속 받기
function Student_Inheritance(grade, classNo){
this.grade = grade;
this.classNo = classNo;
}
//▼ Student_Inheritance의 protype을 통해서 Student를 상속을 받음
Student_Inheritance.prototype = new Student();
var si = new Student_Inheritance(3, 10);
si.info();
//상속을 받은 뒤의 기능 추가
Student_Inheritance.prototype.hobbyInput = function(){
var hobbyInfo = prompt('이 사람의 취미는 무엇입니까?');
this.hobby = hobbyInfo;
console.log('이 사람의 취미는 ' + this.hobby + '입니다.');
};
si.hobbyInput(); //입력 : 게임
console.log(si.hobby); //출력 : 게임
JavaScript의 prototype
- JavaScript에서 상속을 할 때 사용되는 구체적인 수단
function GrandParent(){};
GrandParent.prototype.locationText = `GrandParent's locationText`;
function Parent(){};
Parent.prototype = new GrandParent();
function Children(){};
Children.prototype = new Parent();
var c = new Children();
console.log(c.locationText); //출력 : GrandParent's locationText
prototype chain이란?
- 특정 개체의 값을 사용하려 했는데 해당 값이 정의되어 있지 않다면
상속 받은 prototype들을 점점 거슬러 올라가면서 해당 값을 찾아내는 것
방금 전의 코드를 통해서 console.log(c.locationText);가 실행된 과정을 알아보자.
- 우선 c.locationText이기 때문에 c라는 객체에서 locationText라는 값이 정의되있는가를 찾아본다.
- c.locationText가 없다면 c의 원형인 Children의 prototype에서 locationText 값이 정의되있는가를 찾아본다.
- Children의 prototype에도 locationText이 정의 되어있지 않다면
Children이 상속받은 Parent의 prototype에서 locationText 값이 정의되있는가를 찾아본다. - Parent의 prototype에도 locationText이 정의되어 있지 않다면
Parent가 상속받은 GrandParent의 prototype에서 locationText 값이 정의되있는가를 찾아본다. - GrandParent의 prototype에 locationText가 정의되어 있기 때문에 그 값을 리턴한다.
이렇게 차례대로 연관되어 거슬러 올라가며 상속받은 protype들을 찾는 것이 prototype chain이다.