我正在编写一个在线游戏,它允许用户从一个谜题前进到下一个谜题,如果用户犯错,每个谜题都有一个重新开始按钮,允许用户从头开始那个谜题。代码结构的简化版本如下:
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” - 应该与 this 相同- 正确地提到了第二个谜题。
为什么'this'坚持提到第一个?
如果您需要更多代码示例,请告诉我