Martin
Martin

Reputation: 490

CoffeeScripts classes - access to property in callback

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!

Upvotes: 1

Views: 629

Answers (1)

Michiel
Michiel

Reputation: 274

Because of the scoping of this (or @ in case of CoffeeScript).

You should use a fat arrow:

runBar: =>
  alert @simpleProperty #fooBar

See it working here.

Upvotes: 4

Related Questions