0

我正在编写一个在线游戏,它允许用户从一个谜题前进到下一个谜题,如果用户犯错,每个谜题都有一个重新开始按钮,允许用户从头开始那个谜题。代码结构的简化版本如下:

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'坚持提到第一个?

如果您需要更多代码示例,请告诉我

4

2 回答 2

1

$('#startOver').click(this.empty);

您已经采用了该empty方法并将其分离,this以作为一个普通的未绑定函数传递给 jQuery。当它被回调时,它不会引用 的原始值this。事实上,当一个函数被称为 unbound 时,this将引用window,因此您将在全局变量上写下您认为是属性的内容。

JavaScript 不像其他语言那样绑定方法。参见例如。这个答案解释了它的实际作用。这让很多人感到困惑;我个人认为这是 JavaScript 最严重的缺陷之一。

于 2009-11-18T16:29:33.703 回答
0

在Quirksmode上有一个非常好的(并且清晰的)描述,准确地描述了this在不同上下文中如何处理引用。

于 2009-11-18T16:32:57.170 回答