为什么'this'没有更新来引用新对象?

时间:2009-11-18 16:16:11

标签: javascript jquery object scope 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' - 应该与此相同 - 正确地指的是第二个难题。

为什么'this'一直在引用第一个?

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

2 个答案:

答案 0 :(得分:1)

  

$( '#startOver')上单击(this.empty);

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

JavaScript不会像其他语言一样绑定方法。见例如。 this answer解释它实际上做了什么。这让很多人感到困惑;我个人认为这是JavaScript最糟糕的缺陷之一。

答案 1 :(得分:0)

有一个非常好(且清晰)的描述,确切地说明this引用在Quirksmode的不同上下文中的处理方式。