CoffeeScripts classes - access to property in call

2019-07-27 22:59发布

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!

2条回答
爷的心禁止访问
2楼-- · 2019-07-27 23:24

In my understanding, if you call function foo.runBar(), this pointer will bind with object foo.

So in the function, this.simpleProperty will be deemed to foo.simpleProperty.

Obviously, it returns undefined.

查看更多
Summer. ? 凉城
3楼-- · 2019-07-27 23:50

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.

查看更多
登录 后发表回答