سؤال

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?

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top