2010-02-18 5 views
2

나는 객체를 생성하고 객체의 메소드 설정()를 가지고했습니다.jQuery에서 each()의 범위에있을 때 "this"의 범위를 어떻게 해결합니까?

this.debug = function(){...} 

this.setup = function(){  

    var fieldsets = form.children("fieldset"); 

    fieldsets.each(function(){   
    this.debug($(this).attr("class"))); 
    }); 


} 

내가 본이 다른 때문에, 개체의 범위에 있지만 각각의 범위에있는 this.debug를 호출하기 위해 노력하고있어 ...

어떻게이 액세스합니까 .debug?

답변

5

는 this.debug 후, 다음 that.debugvar that = this 말.

+0

그 didnt work =] lol – qodeninja

+0

미안하지만 농담을 놓치면 실제로 작동하지 않습니까? – Skilldrick

+0

this and that ... that.funny = 101 – neatlysliced

1

jQuery를 1.4에서 당신은 할 수 있습니다 :

this.debug = function(){...} 

this.setup = function(){  

    var fieldsets = form.children("fieldset"); 

    fieldsets.each(jQuery.proxy(function(){ 
    this.debug($(this).attr("class"))); 
    },this); 
} 

jQuery.proxy (함수 객체) 함수는 두 인수를 취합니다

  • 기능은 루프에서 사용되는 기능이 될 것입니다.
  • 오브젝트 인수는 함수 내부 this 객체 것이다.

이렇게하면 each 함수의 바깥 쪽 범위에서 this을 전송할 수 있습니다.

+1

를 모두는이 ... – Skilldrick

+0

정확히 외부 될 것입니다 : - –

+1

매우 유용한'jQuery.each' 기능에 루프 전을 변환; 'var = this;'트릭은 각 익명 함수 내에서 외부 'this'에 의존하는 또 다른 익명 함수를 정의하는 경우에도 잘 작동하지 않습니다. 지역 변수'that'은 내부 함수가 호출되기 전에 사라질 것입니다. –

3

이 기본적으로 Skilldrik의 대답이지만, 가장 내 그리스 몽키 - 콘솔에서이 시도

this.setup = function(){  
    // save it in a scoped var... some people use "self" for this purpose, i prefer 
    // naming it whatever the outer object actually is... 
    var containingObject = this; 

    var fieldsets = form.children("fieldset"); 

    fieldsets.each(function(){   
    // use that scoped var later! 
    containingObject.debug($(this).attr("class"))); 
    });  
} 
+0

+1. 또한 디버그 메소드가 인스턴스 데이터를 사용하지 않는 경우 정적 컨텍스트 인 ContainingObject.debug ($ (this) .attr ("class")));로 호출 할 수 있습니다. – markalex

0

작동 위치를 표시 : 모든 디버그의 범위를 검색합니다

this.debug = function() { 
    console.log("foo"); 
}; 

this.setup = function() { 

    var fieldsets = form.children("fieldset"); 

    fieldsets.each(function(){ 
     debug($(this).attr("class")); 
    }); 
}; 

.. 이것이 희망적으로 위의 기능입니다. 당신이 바로 그 같은 이름 :

+0

'foreach' 루프의'this'는 현재 반복의 fieldset 객체를 포함합니다. – Scharrels

0

내가 일반적으로 그것을 이런 식으로 할 수와 변수를 할당하는 경우는 실패합니다 (참고 : 아래 예제는 메모리에서하지만, 보이는 소리) :

function CustomObject() 
{ 
    var _instance = this; 

    this.debug = function(){...}; 
    this.setup = 
    function() 
    {  
     var fieldsets = form.children("fieldset"); 
     fieldsets.each(
     function() 
     {   
      _instance.debug($(this).attr("class")); 
     }); 
    }; 
} 
0
this.debug = function(){...} 

this.setup = function(){  
    var that = this; 
    var fieldsets = form.children("fieldset"); 

    fieldsets.each(function(){   
    that.debug($(this).attr("class"))); 
    }); 


} 
관련 문제