2010-02-18 80 views
2

我已經創建了一個對象,並在對象中有一個方法setup()。在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

說012herafter this.debug,然後做that.debug

+0

那沒有工作=]大聲笑 – qodeninja 2010-02-18 19:04:43

+0

對不起,如果我錯過了這個笑話,但它確實不起作用? – Skilldrick 2010-02-18 19:07:20

+0

這和那... that.funny = 101 – neatlysliced 2010-02-18 19:20:51

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(函數對象)函數將採取2個參數:

  • 該功能將在循環使用的功能。
  • 對象參數將是該函數內部的this對象。

通過這種方式,您可以從each函數內的外部範圍轉移this

+1

然後這兩個都是外面這個...... – Skilldrick 2010-02-18 19:11:15

+0

正是! '$(this)'以這種方式丟失,因爲它不再是'fieldset' ... – 2013-07-26 12:21:37

+1

將前者for循環轉換爲'jQuery.each'函數非常有用;如果在每個匿名函數中定義了另一個依賴於外部'this'的匿名函數,那麼'var that = this;'技巧就不適用。在調用內部函數之前,局部變量'that'將會消失。 – 2013-10-27 22:29:00

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 2010-02-18 19:38:15

0

我在Greasemonkey的控制檯嘗試這樣做:

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 2010-02-18 19:33:48

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"))); 
    }); 


}