coffeescriptspine.js

Purpose of @ symbol infront of functions


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?


Solution

  • 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/