2014-01-30 112 views
0

請通過代碼JavaScript類澄清

function Item() 
{ 
this.state = 0; 
} 

Item.prototype.SendRequest = function() 
{ 
    //some request callback returns and calls GotResult 
    var that = this; 
    { 
    that.GotResult();//used 'that' because its inside another block 
    } 
} 

Item.prototype.GotResult = function() 
{ 
    //add to local db with callback which calls AddedToLocalDb 
    var that = this; 
    // Here is where the problem is 
    { 
    that.AddedToLocalDb();//..... ERROR 
    } 
} 

Item.prototype.AddedToLocalDb = function() 
{ 
} 

在 「this.AddedToLocalDb()」 我得到它的定義。這是爲什麼?有任何想法嗎? 在該塊上,'this'變量未定義。我犯了一個錯誤還是有一個範圍問題。任何幫助,將不勝感激。

回答

2

當回調函數被調用時,這可能是回調函數和this值丟失的問題。但要確定地知道,你必須展示涉及回調的實際代碼。我們不僅需要看到方法定義,還需要看到使用這些方法導致問題的實際代碼。

我懷疑這是你打電話通過GotResult。如果這個猜測是正確的,那麼你可以通過this.GotResult.bind(this)而不是隻傳遞this.GotResult,它可能會解決你的問題。

這種類型的問題有時可以用你的var that = this技術解決,但只適用於在同一範圍內使用本地函數,而不適用於在同級作用域中定義的方法定義。

+0

非常感謝。這工作。 :) – ArvindSadasivam

+0

順便說一句我加了gotresult.bind(that); – ArvindSadasivam