0

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?

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This plus using the new keyword and you should be set. f = new Foo()
And rewriting the if a == 1 to if Foo::a == 1 since a is also in the prototype.
sorry I omitted the new keyword by it is in the original source. This seems to have worked. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.