2009-11-18 77 views
0

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

为什么'这个'坚持引用第一个?

让我知道如果你需要更多的代码样本

+1

很多这个答案取决于什么是在“重新开始” – cwallenpoole 2009-11-18 16:31:43

回答

1

$( '#startOver')点击(this.empty)。

你从this采取了empty方法和分离它通过为普通绑定功能的jQuery。当它被回叫时,它将不会引用this的原始值。事实上,当一个函数被调用unbound时,this将引用window,所以你会在你认为属性的全部内容上乱涂乱画。

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

+1

这是有点我期望它是,但我已经检查使用console.log和'这个',在这个特定的背景下,不知何故仍然指的是旧版本的window.thePuzzle – wheresrhys 2009-11-18 16:31:46

+1

仍然没有足够的代码来重现该问题,但是我的怀疑可能会在代码中的某处出现,因为代码中的'window.thePuzzle'被'拼图“构造函数,比如'init'或'addListeners'。那时,说'window.thePuzzle = new puzzle'的'puzzleSequence'代码不会将新对象写入'window.thePuzzle',但它不能,直到构造函数完成执行。 – bobince 2009-11-18 18:34:33

0

关于this参考文献在不同情况下如何处理Quirksmode有很好的(和清楚的)描述。

相关问题