rdodev
rdodev

Reputation: 3192

CoffeeScript instance methods

I have a CoffeeScipt class defined like such

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

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

it keeps erroring out saying that log is not defined. I tried making it @log: didn't work either. I tried making the -> of main a => and did not work either. How can I call instance methods from within the class itself?

Upvotes: 0

Views: 937

Answers (1)

Sergey Metlov
Sergey Metlov

Reputation: 26291

Use @ when calling instance methods and fields not when defining:

class Foo
  a: 1
  b: 2

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

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

f = new Foo()
f.main()

Defining methods with @ like this

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

makes them static.
Look at the compiled JS while developing on CoffeeScript.

Upvotes: 9

Related Questions