admin管理员组

文章数量:1279021

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.

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.

Share Improve this question edited Jul 7, 2012 at 23:37 Jamie Fearon asked Jul 7, 2012 at 23:10 Jamie FearonJamie Fearon 2,63413 gold badges49 silver badges65 bronze badges 1
  • requestAnimationFrame doesn't take a number as the second argument; instead, it calls the given function ASAP (typically faster than setTimeout(func, 0) does) provided that the browser tab is in the foreground. See developer.mozilla/en/DOM/window.requestAnimationFrame – Trevor Burnham Commented Jul 8, 2012 at 1:04
Add a ment  | 

2 Answers 2

Reset to default 11

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)

本文标签: javascriptInstance variable becomes undefinedCoffeeScriptStack Overflow