我正在写一个在线游戏,允许用户从一个谜题进展到下一个谜题,如果用户犯了错误,每个谜题都有一个重新开始按钮,允许用户从头开始创建这个谜题。代码的结构的简化版本如下:为什么'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