2009-11-18 63 views
0

我正在寫一個在線遊戲,允許用戶從一個謎題進展到下一個謎題,如果用戶犯了錯誤,每個謎題都有一個重新開始按鈕,允許用戶從頭開始創建這個謎題。代碼的結構的簡化版本如下:爲什麼'this'沒有更新來引用新對象?

function puzzle(generator) { 

    this.init = function() { 
     this.generator = generator; 
     ... 
     this.addListeners(); 
    } 

    //fires when the puzzle is solved 
    this.completed = function() { 
     window.theSequence.next(); 
    } 

    this.empty = function() { 
     //get rid of all dom elements, all event listeners, and set all object properties to null; 
    } 

    this.addListeners = function() { 
     $('#startOver').click(function() { 
      window.thePuzzle.empty(); 
      window.thePuzzle.init(); 
     }); 
    } 
    this.init(); 
} 

function puzzleSequence(sequenceGenerator) { 

    this.init = function() { 
     //load the first puzzle 
     window.thePuzzle = new puzzle({generating json}); 

    } 

    this.next = function() { 
     //destroy the last puzzle and create a new one 
     window.thePuzzle.empty(); 
     window.thePuzzle = new puzzle({2nd generating json}); 
    } 

} 

window.theSequence = new puzzleSequence({a sequence generator JSON}); 

我的問題是,如果用戶已經發展到第二個謎,如果他們點擊重新開始加載第一個謎題,而不是第二。經過一些調試後,我發現'this'在用於第二個謎題的方法中時由於某種原因仍然引用了第一個謎題,但'window.thePuzzle' - 應該與此相同 - 正確地指第二個難題。

爲什麼'這個'堅持引用第一個?

讓我知道如果你需要更多的代碼樣本

+1

很多這個答案取決於什麼是在「重新開始」 – cwallenpoole 2009-11-18 16:31:43

回答

1

$( '#startOver')點擊(this.empty)。

你從this採取了empty方法和分離它通過爲普通綁定功能的jQuery。當它被回叫時,它將不會引用this的原始值。事實上,當一個函數被調用unbound時,this將引用window,所以你會在你認爲屬性的全部內容上亂塗亂畫。

JavaScript不像其他語言那樣綁定方法。見例如。 this answer以解釋它實際做了什麼。這讓很多人感到困惑。我個人認爲這是JavaScript最糟糕的缺陷之一。

+1

這是有點我期望它是,但我已經檢查使用console.log和'這個',在這個特定的背景下,不知何故仍然指的是舊版本的window.thePuzzle – wheresrhys 2009-11-18 16:31:46

+1

仍然沒有足夠的代碼來重現該問題,但是我的懷疑可能會在代碼中的某處出現,因爲代碼中的'window.thePuzzle'被'拼圖「構造函數,比如'init'或'addListeners'。那時,說'window.thePuzzle = new puzzle'的'puzzleSequence'代碼不會將新對象寫入'window.thePuzzle',但它不能,直到構造函數完成執行。 – bobince 2009-11-18 18:34:33

0

關於this參考文獻在不同情況下如何處理Quirksmode有很好的(和清楚的)描述。