我正在寫一個在線遊戲,允許用戶從一個謎題進展到下一個謎題,如果用戶犯了錯誤,每個謎題都有一個重新開始按鈕,允許用戶從頭開始創建這個謎題。代碼的結構的簡化版本如下:爲什麼'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' - 應該與此相同 - 正確地指第二個難題。
爲什麼'這個'堅持引用第一個?
讓我知道如果你需要更多的代碼樣本
很多這個答案取決於什麼是在「重新開始」 – cwallenpoole 2009-11-18 16:31:43