자바스크립트 상속 4


4. 생성자 빌려쓰기를 통한 다중 상속


  1. var Inherit = (function(){
  2.    
  3.     function Parent1(name){
  4.         this.name = name;
  5.         return this;
  6.     }
  7.  
  8.     Parent1.prototype.getName = function(){
  9.         return this.name;
  10.     };
  11.  
  12.     function Parent2(title){
  13.         this.title = title;
  14.         return this;
  15.     }
  16.  
  17.     Parent2.prototype.getTitle = function(){
  18.         return this.title;
  19.     };
  20.  
  21.  
  22.     function Child(name, title){
  23.         Parent1.call(this, name);
  24.         Parent2.call(this, title);
  25.         return this;
  26.     };
  27.  
  28.     return new Child('name', 'title');
  29.    
  30. })();
  31.  
  32. alert(Inherit.name); // name
  33. alert(Inherit.title); // title


다중 상속 구조를 설명하면 아래와 같습니다.

1. Parent1 생성자 함수에 인스턴스 맴버 name 속성을 추가 합니다.
 
2. Parent1 생성자 함수에 프로토타입 맴버 getName 메서드를 추가 합니다.
 
3. Parent2 생성자 함수에 인스턴스 맴버 title 속성을 추가 합니다.
 
4. Parent2 생성자 함수에 프로토타입 맴버 getTitle 메서드를 추가 합니다.
 
5. Child 생성자 함수 내부에서 Function.prototype.call() 메서드를 활용하여 Parent1 생성자
함수와 Parent2 생성자 함수의 인스턴스 맴버를 Child 생성자 함수의 맴버로 복사한다.
 
6. Child 생성자 함수의 프로토타입 맴버에 new Parent 객체를 추가 합니다.
 
7. new Child 객체를 반환 합니다.
 
8. 여기서 new Child 객체는 new Parent 객체의 인스턴스 맴버 모두(name)를 상속 받습니다.
(이전과 달리 프로토타입 맴버를 상속받지 않는 이유는 다중 상속 구조에서는 프로토타입
맴버를 추가 할 수 없기 떄문입니다.)
 
9. alert(Inherit.name);과 alert(Inherit.title);의 반환값이 각각 'name', 'title'이 나오는 이유는 5번 내용과 같이 Child 생성자 함수 내부에서 Function.prototype.call() 메서드를 활용하여 Parent1 생성자 함수와 Parent2 생성자 함수의 인스턴스 맴버를 Child 생성자 함수의 맴버로 복사하고, 그와 동시에 각가의 생성자 함수의 인자값('name', 'title') 또한 주었기 때문입니다.