2013-08-07 3 views
0

JavaScript를 처음 사용하고 매개 변수를 사용하는 생성자가있을 때 상속 받기에 주저하고 있습니다. 가정하자매개 변수가있는 생성자를 사용하여 JavaScript 상속

나는 기본 객체가 Base라고 있습니다

function Base(param1, param2) { 
    // Constructor for Base that does something with params 
} 

내가 다른 개체를 원하는, 예를 들어 자료에서 상속 BaseChild라고하고 또 다른 목적은 BaseChild에서 상속 Child을했다.

가 어떻게 기본 자바 스크립트 (즉, 특별한 플러그인)을 사용하지 BaseChildChild에 대한 생성자를 만드는 방법에 대해 갈 것 ?


참고 :에,

var BaseChild = new Base(param1, param2);

을하지만 BaseChildparam1 또는 param2의 값을 가지고 있지 않습니다

나는 다음과 같이 BaseChild을 만들 수있을 거라고 생각 Child. 나는 이것이 의미가 있기를 바란다!.

+0

중복 가능성 [자바 스크립트의 생성자 함수에서 상속 생성자 함수를 얻는 방법?] (http://stackoverflow.com/ 질문/2263353/how-to-get-a-constructor-function-to-a-constructor-function-in-java) – Bergi

답변

1
// define the Base Class 
function Base() { 
    // your awesome code here 
} 

// define the BaseChild class 
function BaseChild() { 
    // Call the parent constructor 
    Base.call(this); 
} 

// define the Child class 
function Child() { 
    // Call the parent constructor 
    BaseChild.call(this); 
} 


// inherit Base 
BaseChild.prototype = new Base(); 

// correct the constructor pointer because it points to Base 
BaseChild.prototype.constructor = BaseChild; 

// inherit BaseChild 
Child.prototype = new BaseChild(); 

// correct the constructor pointer because it points to BaseChild 
Child.prototype.constructor = BaseChild; 
Object.create를 사용

다른 방법

BaseChild.prototype = Object.create(Base.prototype); 
Child.prototype = Object.create(BaseChild.prototype); 
관련 문제