사용자가 한 퍼즐에서 다음 퍼즐로 진행할 수있는 온라인 게임을 작성 중입니다. 사용자가 실수를하면 각 퍼즐에 다시 시작 버튼이있어서 사용자는 처음부터 그 퍼즐을 시작할 수 있습니다. 코드의 구조의 단순화 된 버전은 다음과 같습니다 :'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'가 첫 번째 참조를 계속 유지합니까?
더 많은 코드 샘플
필요하면 알려주세요
이 답변의 대부분은 "처음부터 끝"에있는 것입니다. – cwallenpoole