Jam*_*ron 5 javascript 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()
Run Code Online (Sandbox Code Playgroud)
Game中animate方法的登录产生:
foo = 2
foo =未定义
所以foo在第一次调用动画时是2,然后是未定义的.有人可以解释为什么以及如何解决这个问题.任何帮助深表感谢.
Aar*_*our 11
当你打电话时setInterval,上下文丢失,第二次@是window.您需要使用fat-arrow方法来保留适当的方法this:
animate: =>
Run Code Online (Sandbox Code Playgroud)
您可以定义animate如下:
animate: ->
callback = (=> @animate())
requestAnimationFrame(callback, 1000 )
console.log('foo = ', @foo)
Run Code Online (Sandbox Code Playgroud)
这里的技术是获得绑定方法.@animate它本身是未绑定的,但它(=> @animate())是它的绑定版本.
如果您使用UnderscoreJS,您可以获得类似的结果,如下所示:
animate: ->
callback = _.bind(@animate, @)
requestAnimationFrame(callback, 1000 )
console.log('foo = ', @foo)
Run Code Online (Sandbox Code Playgroud)
如果您使用的是更高版本的JavaScript,则可以执行以下操作:
animate: ->
callback = @animate.bind(@)
requestAnimationFrame(callback, 1000 )
console.log('foo = ', @foo)
Run Code Online (Sandbox Code Playgroud)