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 thansetTimeout(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
2 Answers
Reset to default 11When 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
版权声明:本文标题:javascript - Instance variable becomes undefined - CoffeeScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741267841a2368816.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论