자바스크립트 상속 1


1. 클래스 방식 상속 1


  1. var Inherit = (function(){
  2.    
  3.     function Parent(){
  4.         this.name = 'parent';
  5.         return this;
  6.     }
  7.  
  8.     Parent.prototype.getName = function(){
  9.         return this.name;
  10.     };
  11.  
  12.  
  13.     function Child(){
  14.         return this;
  15.     };
  16.  
  17.    
  18.     Child.prototype = new Parent();
  19.  
  20.     return new Child();
  21.  
  22.  
  23. })();
  24.  
  25.  
  26. alert(Inherit.getName()); // parent
  27.  
 

위 코드가 가장 널리 쓰이며, 가장 기본적인 상속 방법 입니다.


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

1. Parent 생성자 함수에 인스턴스 맴버 name 속성을 추가 합니다.
 
2. Parent 생성자 함수에 프로토타입 맴버 getName 메서드를 추가 합니다.
 
3. Child 생성자 함수의 프로토타입 맴버에 new Parent 객체를 추가 합니다.
 
4. new Child 객체를 반환 합니다.
 
5. 여기서 new Child 객체는 new Parent 객체의 맴버그룹(인스턴스, 프로토타입)
모두(name, getName())를 상속 받습니다.

6. alert(Inherit.getName()); 반환값이 Parent가 나오는 이유는 5번 내용과 같이 new Parent
객체의 맴버를 모두 상속 받았기 때문입니다.

또한, 상속 과정을 거친 프로토타입은 아래처럼 서로 연결 됩니다.

--> (_proto_ 속성이 가리키는 방향)

new Child --> (Child.prototype : Object.prototype) --> new Parent (member: name) --> (Parent.prototype (member: getName()) : Object.prototype)