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 log in the animate method in Game produces:
foo = 2
foo = undefined
So foo is 2 on the first call to animate and then undefined thereafter. Could someone please explain why and how I can fix this. Any help is much appreciated.
if (typeof MyVariable !== "undefined" && MyVariable !==
An instance variable is just a property of an object, as Felix Kling said. You can't use props because that's referencing a global or local variable called props . What you want to access is the current value of props for the current component, stored in this.
When you call setInterval, context is lost and the second time @ is window.  You need fat-arrow methods to retain the appropriate this:
animate: =>
                        You can define animate as follows:
animate: ->
  callback = (=> @animate())
  requestAnimationFrame(callback, 1000 )
  console.log('foo = ', @foo)
The technique here is to get a bound method. @animate by itself is unbound, but (=> @animate()) is the bound version of it.
You can get a similar results if you're using UnderscoreJS as follows:
animate: ->
  callback = _.bind(@animate, @)
  requestAnimationFrame(callback, 1000 )
  console.log('foo = ', @foo)
And if you are using a later version of JavaScript, you may be able to do as follows:
animate: ->
  callback = @animate.bind(@)
  requestAnimationFrame(callback, 1000 )
  console.log('foo = ', @foo)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With