Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 254
Jamie Fearon Avatar asked Jul 07 '12 23:07

Jamie Fearon


People also ask

How do you check for undefined in Coffeescript?

if (typeof MyVariable !== "undefined" && MyVariable !==

What is instance variable in JS?

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.


2 Answers

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

animate: =>
like image 185
Aaron Dufour Avatar answered Nov 04 '22 22:11

Aaron Dufour


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)
like image 5
yfeldblum Avatar answered Nov 04 '22 22:11

yfeldblum