자바스크립트 상속 2


2. 클래스 방식 상속 1 - 1

 
  1. var Inherit = (function(){
  2.    
  3.     function Parent(){
  4.         this.names = [1];
  5.         return this;
  6.     }
  7.  
  8.     Parent.prototype.getNames = function(){
  9.         return this.names;
  10.     };
  11.  
  12.  
  13.     function Child(){
  14.         return this;
  15.     };
  16.  
  17.     var p = new Parent();
  18.    
  19.     // 자바스크립에서 객체는 참조만 전달되기 때문에, 위와 같이 자식객체(new Parent)에서 names 맴버 속성을 수정하면 부모의 names 맴버 속성까지 수정된다.
  20.     p.names.push(2);
  21.     Child.prototype = p;
  22.  
  23.     return new Child();
  24.  
  25. })();
  26.  
  27. alert(Inherit.getNames()); // 1, 2


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

1. Parent 생성자 함수에 인스턴스 맴버 name 속성을 추가 합니다.
 
2. Parent 생성자 함수에 프로토타입 맴버 getName 메서드를 추가 합니다.
 
3. new Parent 객체의 names 맴버 속성을 수정한 후 Child 생성자 함수의 프로토타입 맴버에
new Parent 객체를 추가 합니다.
 
4. new Child 객체를 반환 합니다.
 
5. 여기서 new Child 객체는 new Parent 객체의 맴버(인스턴스, 프로토타입)
모두(name, getName())를 상속 받습니다.
 
6. alert(Inherit.getName()); 반환값이 1, 2가 나오는 이유는 5번 내용과 같이 수정된 new Parent
객체의 맴버를 모두 상속 받았기 때문입니다.