Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoffeeScript - understanding "@"

I have read several papers on CoffeeScript OOP. From them, do I understand correctly that using the @ sign in CoffeeScript (and this prefix in JavaScript):

  • for variables: makes variables members of a class instance. Each instance has it's own such variable (non-static variable)
  • for "methods": makes methods static, which is contrary to what it does with variables

I am a noob in JS and CS, sorry. Their philosophy is quite different from what I am used to.

UPDATE

Here are references on the info that I have read:

  • reference-1
  • reference-2

just search for static.

like image 271
noncom Avatar asked Aug 29 '26 00:08

noncom


1 Answers

Inside a method, @ is JavaScript's this and refers to the current object; the current object depends on how the method is called, see call and apply for ways to mess around with a method's @ (AKA this); you can also use => to bind a method to an object in CoffeeScript.

If you say @p = 11, that's the same as this.p = 11 and makes p available in that object.

Inside a class definition, @ refers to the class itself. So this:

class C
    @m: -> ...

defines a class method and you can say C.m() to execute it.

Consider this example:

class C
    a: -> @p = 11
    b: -> console.log(@p)
    @c: -> console.log('Class method')

C.c()            // This calls the class method.
o = new C
o.b()            // There is no 'o.p' yet.
o.a()            // This sets 'o.p'.
o.b()            // And now we see an 'o.p'.
console.log(o.p) // And we see o.p here as well.

That will give you this output in the console:

Class method
undefined
11
11

Demo: http://jsfiddle.net/ambiguous/DFcRt/

These might also be of interest:

  • Variable types in CoffeeScript
  • How to make method private and inherit it in Coffeescript? ​
like image 172
mu is too short Avatar answered Aug 30 '26 15:08

mu is too short



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!