1

我有简单的问题。我有 Foo 类,并且在构造函数中我开始计时器。在计时器回调中,我想要警报类属性,但我会得到“未定义”,为什么?

class Foo
  simpleProperty: "fooBar"

  constructor: ->
    setInterval @runBar, 1 * 1000
    return

  runBar: ->
    alert @simpleProperty #undefined, why?
    return

foo = new Foo()

感谢您的帮助!

4

1 回答 1

4

因为this(或@在 CoffeeScript 的情况下)的范围。

您应该使用粗箭头:

runBar: =>
  alert @simpleProperty #fooBar

看到它在这里工作。

于 2012-11-15T12:24:00.820 回答