I am trying to do setInterval inside a class and the code below works fine in the sense that as the car is created a call to its updatePosition is periodically called.
The problem is that I can not get the value of the @currentSpeed variable in the setInterval “scope”. Instead I get “Updating position: Speed: undefined” in my console.log when the updatePosition function is invoked by the interval.
When I call accelerate() function (which is called anytime I hit the accelerate button) it returns the expected @currentSpeed value
How can I get the value from @currentSpeed in the setInterval scope?
Here is the relevant part of my code:
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}"
There is no point in doing
do => @updatePositionto create a callback – because this creates a function (=>) that is immediately executed (due to thedokeyword) and returns the function@updatePosition. Thus, you can simplify this to@updatePosition.The fat arrow is required at a different location: updatePosition() needs access to the current instance, in order to retrieve the value for @currentSpeed – but since you cannot ensure that this function will always be called in the correct context, you need to bind it to this function by using the fat arrow: