实例变量变为未定义 - CoffeeScript

时间:2012-07-07 23:10:38

标签: javascript coffeescript

class Game

  foo: null

  play: ->

    @foo = 2
    @animate()

  animate: ->

    requestAnimationFrame( @animate, 1000 )
    console.log('foo = ', @foo)


$ ->
  game = null

  init = ->

    game = new Game()
    game.play()

  init()

Game中的animate方法中的日志产生:

foo = 2

foo = undefined

所以foo在第一次调用动画时是2,然后是未定义的。有人可以解释为什么以及如何解决这个问题。非常感谢任何帮助。

2 个答案:

答案 0 :(得分:11)

当您致电setInterval时,上下文将丢失,第二次@window。您需要使用fat-arrow方法来保留适当的this

animate: =>

答案 1 :(得分:5)

您可以按如下方式定义animate

animate: ->
  callback = (=> @animate())
  requestAnimationFrame(callback, 1000 )
  console.log('foo = ', @foo)

这里的技术是获得绑定方法。 @animate本身是未绑定,但(=> @animate())是其绑定版本。

如果你使用UnderscoreJS,你可以得到类似的结果:

animate: ->
  callback = _.bind(@animate, @)
  requestAnimationFrame(callback, 1000 )
  console.log('foo = ', @foo)

如果您使用的是更高版本的JavaScript,则可以执行以下操作:

animate: ->
  callback = @animate.bind(@)
  requestAnimationFrame(callback, 1000 )
  console.log('foo = ', @foo)
相关问题