I have simple problem. I have Foo class and at contructor I starting timer. In timer callback I want alert class property, but I will get "undefined", why?
class Foo
simpleProperty: "fooBar"
constructor: ->
setInterval @runBar, 1 * 1000
return
runBar: ->
alert @simpleProperty #undefined, why?
return
foo = new Foo()
Thank you for your help!
In my understanding, if you call function
foo.runBar()
,this
pointer will bind with objectfoo
.So in the function,
this.simpleProperty
will be deemed tofoo.simpleProperty
.Obviously, it returns
undefined
.Because of the scoping of
this
(or@
in case of CoffeeScript).You should use a fat arrow:
See it working here.