2010-09-02 50 views
0

我有一個JavaScript類是這樣的:JavaScript類 - 每個用途都需要「this.varname」嗎?

function Foo() { 
    this.x = 5; 
    this.y = x + 10; 
} 

是「X」得不到作用域類的實例時,我不使用」。這?如果是這樣,那麼我們如何使用回調呢?我有類似:

function Foo() { 
    this.x = 5; 

    this.grok = function() { 
    jQuery(blah).animate({ 
     .., 
     function(){ 
     x = 55; 
     } 
    }); 
    } 
} 

這樣的jQuery給出了一個回調的機會,但我怎麼訪問父類的「X」的成員變量在這種情況下呢?

感謝

回答

1

在特定情況下,你必須向this參考存儲在另一個變量:

function Foo() { 
    this.x = 5; 

    this.grok = function() { 
     var that = this; 
     jQuery(blah).animate({ 
     .., 
     function(){ 
      that.x = 55; 
     } 
     }); 
    } 
} 

匿名函數可以訪問在grok定義的所有變量。如果你只是使用x,這將是一個全局變量。

+0

好的,我也需要一直使用「this」。在每次訪問成員變量之前,對嗎?謝謝 – user246114 2010-09-02 22:27:23

+0

@ user246114:是的。但請注意你在哪個範圍內(如'animate'回調函數中)。 – 2010-09-03 05:08:24

1

你可以做的是使用另一個變量的指針正確這個然後用封閉來捕獲變量:

function Foo() { 
    this.x = 5; 
    var foo_this = this; 

    this.grok = function() { 
    jQuery(blah).animate({ 
     .., 
     function(){ 
     foo_this.x = 55; 
     } 
    }); 
    } 
} 

有些人喜歡用變量名that,每當他們點到this。我個人更喜歡使用self

相關問題