gpt4 book ai didi

javascript - 实例变量变为未定义 - CoffeeScript

转载 作者:数据小太阳 更新时间:2023-10-29 05:44:37 25 4
gpt4 key购买 nike

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()

Game中animate方法中的日志产生:

富 = 2

foo = 未定义

因此 foo 在第一次调用 animate 时为 2,此后未定义。有人可以解释为什么以及如何解决这个问题。非常感谢任何帮助。

最佳答案

当您调用 setInterval 时,上下文丢失,第二次 @window。您需要粗箭头方法来保留适当的 this:

animate: =>

关于javascript - 实例变量变为未定义 - CoffeeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11379378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com