2010-06-29 5 views
2

두 객체를 사용하여 함수 호출 체인을 만들려고합니다.중첩 된 함수 매개 변수와 'this'context in Javascript

내가 할 노력하고있어 설명하기 위해 코드에 주석을 추가 한 :

function Huh(parentContext) { 
this.parentContext = parentContext; 
this.check = function() { 
    console.log(parentContext); 
} 
this.DoWork = function(successFunc) { 
    console.log('Huh.DoWork'); 
    successFunc('yay');  
};} 

function Thing() { 
this.nextSuccess = function(e) {  
    console.log('nextSuccess ' + e); 
}; 

this.success = function(e) { 
    console.log('success!! ' + e); 

    var h = new Huh(this); // It looks like 'this' doesn't mean the Thing context any more. ?!?! 
    //h.check();  
    h.DoWork(this.nextSuccess); // THIS BREAKS. 
}; 

this.fail = function() { 
    console.log('fail'); 
}; 

this.firstBit = function(successFunc, failFunc) { 
    var h = new Huh(this); 
    //h.check();   
    h.DoWork(this.success);  
}; 

// start with this function 
this.Go = function() { 
    this.firstBit(this.success, this.fail); 
};} 

그것은 모든 휴식을 내가 Thing.success에서 허의 두 번째 인스턴스를 만들려고 할 때.

나는 this.nextSuccess를 전달하려하지만 'this'컨텍스트가 더 이상 같지 않은 것처럼 보입니다.

도와주세요.

+2

중첩 된 기능을 사용하는 경우 들여 쓰기에이 기능을 반영하십시오. 그것은 훨씬 쉽게 읽을 수 있습니다. – Skilldrick

+0

죄송합니다. 들여 쓰기를 시도했지만 코드 블록이 계속 손상되었습니다. –

답변

7

Thing 기능의 시작 부분에 var that = this;을 입력하십시오. 을 사용하여 Thingthis에 액세스 할 수 있습니다.

+1

고마워. 원래 코드에서 실패한 이유를 설명 할 수 있다고 생각하지 않습니까? 나는 더 나은 이해를 얻고 싶다. –

+0

awesome : D 덕분에 도움을 얻을 수있다. –

관련 문제