我昨天在javascript中使用coffeescript做了一个简单的游戏。游戏的大部分运行在用户在页面上提交表单后实例化的game
对象中。该表格包含他们想要玩的游戏的变量和选项。如何完全清除javascript对象的属性值和引用?
在游戏中一切正常,但游戏结束后,我再次出现表单,如果用户第二次提交表单,它应该调用相同的函数,并用新实例覆盖旧的game
变量game
对象,但我注意到它不重置原始游戏对象设置的所有现有变量和参数。
当新实例被实例化时,有什么办法可以完全删除旧对象及其参数吗?
这是我的对象在coffeescript中被声明为'class'。
window.Game = class Game
constructor: (options) ->
players = options[0] ? '1'
p1 = p2 = false
@player1 = new Player(options[1] ? 'X', p1)
@player2 = new Player(options[2] ? 'O', p2)
@cells = ($ "section#board .cell")
@cells.each ->
$(@).text(" ")
$(@).removeClass('score')
@currentPlayer = @player1
@availableMoves = 9
($ 'section#board div.cell').bind
click: @.makeMove
mouseleave: @.resetCell
setTimeout(@.computerMove(@currentPlayer), 1000) if parseInt(players) is 0
我在通过此函数提交表单后调用此函数。
($ '#gameOptions').submit (event) ->
event.target.checkValidity()
event.preventDefault()
game = new Game [($ '#player-count') .val(),
($ '#player-1-type').val(),
($ '#player-2-type').val()]
即使在重新实例化游戏对象之前添加调用delete game
也是如此。幻影变量依然存在。为了简洁起见,我发布了咖啡信息以提高可读性。
[如何快速清除Javascript对象?](http://stackoverflow.com/questions/684575/how-to -quickly-clear-a-javascript-object) – maxedison 2012-03-05 22:52:16
possible dup http://stackoverflow.com/questions/742623/deleting-objects-in-javascript – elclanrs 2012-03-05 22:52:28
这里已经被问过很多次了。只是搜索来删除对象的JavaScript。 – maxedison 2012-03-05 22:52:33