2012-01-07 4 views
0

js 프로토 타입을 상속하려고하는 중 일부 문제가 있습니다. 문제는 하위 클래스에서 마스터에서 파생 된 경우 마스터의 initX 메서드는 "this"를 통해 메서드로 알려져 있지 않습니다. JS 프로토 타입 : 아직 파생되지 않은 부모 메서드에 액세스

TypeError: this.initX is not a function 

그래서 기본적으로 어머니 초기화를 호출하지만 그것은 어머니 초기화로 인해 this.initX의 오류가 발생합니다 : Firbug에서

function master() {}; 
function sub() {}; 

master.prototype = { 
    init: function() { 
     console.log('Master Init!'); 
     this.initX();     // This is where the error is thrown 
    }, 
    initX: function() { 
     console.log('Master InitX'); 
    } 
}; 

sub.prototype = new master(); 
sub.prototype.constructor = sub; 
sub.parent = master.prototype; 

sub.prototype.init = function() { 
    sub.parent.init.call(); 
    console.log('Sub Init'); 
} 

var subby = new sub(); 
subby.init(); 

오류 메시지입니다.

누구나 아이디어가 있으십니까?

답변

1

실제로는 this 값을 전달하지 않으므로 window 내에서 init과 같습니다. window.initX 존재하지 않습니다. 이 약자로

.call() 꽤 쓸모가 - 사용하는 대신 다음

sub.parent.init.call(this); // set `this` inside `init`, so that 
          // you'll be calling `initX` on the instance 

당신이뿐만 아니라 인수를 통해 함께 .applyarguments과 함께 모든 것을 전달하는 일반적인 방법 전달하려는 경우

sub.parent.init.apply(this, arguments); 
+0

감사합니다. 그게 효과가 있었어! –