0

I cant understand exactly what @ (this) does infront of class functions. I am using Spine framework, and I got a class Contact which extends Spine.model. I override the Spine methods for creating, deleting, fetching etc, and have them print on the console first like this:

  create: ->
    console.log('create') 
    super

  destroy: ->
    console.log("destroy")
    super

Some of these methods will work the same if I add @ infront, for example create, while others will not work without @, and others will not work with @. All the methods I override can be seen on the link above.

Is it possible to explain me the effect of @ symbol infront of functions, and why its causing this behaviour?

Giannis
  • 5,286
  • 15
  • 58
  • 113
  • 1
    `@identifier` is just `this.identifier`. See http://coffeescript.org/#operators. – Rob W Jun 23 '13 at 13:54
  • Yes I understand its use infront of variables, just not what it does infront of functions, and why the above examples behave like this. – Giannis Jun 23 '13 at 13:57
  • @Glannis Some functions are instance methods, whereas others are just local variables. Can you point to a specific example in the code which caused confusion (edit the question)? – Rob W Jun 23 '13 at 14:01
  • The app I am working with is the Contacts example of the spinejs framework http://spinejs.com/docs/example_contacts . In this example the fetch function requires @ to print. destroy function does not print if @ is added. On every case, application behaves normally, just the printing changes. – Giannis Jun 23 '13 at 14:05

1 Answers1

0

Answer from mu is too short : You can define class methods by prefixing them with @:

class Box2DUtility
  constructor: () ->
  @drawWorld: (world, context) -> alert 'World drawn!

'

And then draw your world...

Box2DUtility.drawWorld()

Demo: http://jsfiddle.net/ambiguous/5yPh7/

And if you want your drawWorld to act like a constructor then you can say new @ like this:

    class Box2DUtility
      constructor: (s) -> @s = s
      m: () -> alert "instance method called: #{@s}"
      @drawWorld: (s) -> new @ s

Box2DUtility.drawWorld('pancakes').m()

Demo: http://jsfiddle.net/ambiguous/bjPds/1/

Giannis
  • 5,286
  • 15
  • 58
  • 113