0

我有一个像这样定义的 CoffeeScipt 类

class Foo
  a: 1
  b: 2
  main: ->
   if a == 1
    log(1)

  log: (num) ->
    console.log(num)
f = new Foo
f.main()

它不断出错,说未定义日志。我试着让它@log:也不起作用。我尝试制作->main a=>并没有工作。如何从类本身调用实例方法?

4

1 回答 1

9

@在调用实例方法和字段时使用,而不是在定义时使用:

class Foo
  a: 1
  b: 2

  main: ->
   if @a == 1
    @log(1)

  log: (num) ->
    console.log(num)

f = new Foo()
f.main()

@像这样定义方法

@log: (num) ->
    console.log(num)

使它们成为静态的。
在 CoffeeScript 上开发时查看编译后的 JS。

于 2013-07-12T16:57:04.467 回答