如何在coffeescript类中使用setInterval作用域?
我试图在一个类中执行setInterval,下面的代码工作得很好,因为在创建汽车时,会定期调用对其updatePosition的调用 问题是我无法获得setInterval“范围”中@currentSpeed变量的值。相反,当间隔调用updatePosition函数时,我在我的console.log中得到“updatePosition:Speed:undefined” 当我调用accelerate()函数时(每当我按下accelerate按钮时都会调用该函数),它将返回预期的@currentSpeed值 如何从setInterval范围内的@currentSpeed获取值 以下是我的代码的相关部分:如何在coffeescript类中使用setInterval作用域?,coffeescript,setinterval,Coffeescript,Setinterval,我试图在一个类中执行setInterval,下面的代码工作得很好,因为在创建汽车时,会定期调用对其updatePosition的调用 问题是我无法获得setInterval“范围”中@currentSpeed变量的值。相反,当间隔调用updatePosition函数时,我在我的console.log中得到“updatePosition:Speed:undefined” 当我调用accelerate()函数时(每当我按下accelerate按钮时都会调用该函数),它将返回预期的@currentSp
class Car
constructor: () ->
@currentSpeed = 0
intervalMs = 1000
@.setUpdatePositionInterval(intervalMs)
setUpdatePositionInterval: (intervalMs) ->
setInterval (do => @updatePosition ), intervalMs
updatePosition: () ->
# below logs: "Updating position: Speed: undefined"
console.log("Updating position: Speed: #{@currentSpeed}")
accelerate: () ->
#below logs the expected value of @currentSpeed
console.log "ACCELERATING! CurrentSpeed: #{@currentSpeed}"
执行
do=>@updatePosition
来创建回调没有意义,因为这会创建一个立即执行的函数(=>
),并返回函数@updatePosition
)。因此,您可以将其简化为@updatePosition
在不同的位置需要fat箭头:updatePosition()需要访问当前实例,以便检索@currentSpeed的值-但由于无法确保始终在正确的上下文中调用此函数,因此需要使用fat箭头将其绑定到此函数:
setUpdatePositionInterval: (intervalMs) ->
setInterval @updatePosition, intervalMs
updatePosition: () =>
console.log("Updating position: Speed: #{@currentSpeed}")
这也是可能的,但还需要一对括号才有效;)
setInterval (=> @updatePosition()), intervalMs