Instance variable becomes undefined - 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()

The magazine in the animation mode in the game gives:

foo = 2

foo = undefined

So foo is 2 on the first animation call, and then undefined. Can someone explain why and how I can fix this. Any help is greatly appreciated.

+5
source share
2 answers

When you call setInterval, the context is lost, and the second @- window. You need bold arrow methods to keep the appropriate this:

animate: =>
+11
source

You can define animateas follows:

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)
+5

All Articles