I’m not quite sure the uses for the different variables in CoffeeScript
class Cow
@utters = 1
constructor: (@name) ->
mutate:->
alert @utters
heads: 1
feet = 9
c = new Cow
From my investigation, it seems heads is public and feet is private. My confusion comes in when figuring out name and utters. For name it more or less compiles to this.name = name and for utters it compiles to Cow.utters = 1.
So my questions are. What is the scope of utters and how should it be accessed? What is the scope of name and how should it be accessed?
Let us look at these one by one.
For the first one:
thisis the class itself when you hit@utters = 1so this@uttersis sort of a class variable. The JavaScript version is this:Subclasses will be able to see this but they’ll have their own copy of it; so, for this:
CowCow.uttersstarts out as 1 but will be 11 after(new CowCow).m()andCow.utterswill stay at 1 all the way through.The second one:
is essentially a default instance variable; the JavaScript version looks like this:
The
Cow.prototype.heads = 1;part means thatheadsis inherited and attached to instances rather than classes.The result is that this:
alerts 1 twice.
The third one:
is another sort of class variable but this one is very private:
feetis not inherited, not visible to subclasses, and not visible to the outside world. The JavaScript version is this:so you can see that:
feetwill be visible to allCowmethods.Cowinstances will share the samefeet.feetis not public in that you can’t get at it without calling aCowmethod (class or instance, either will do).feetis not visible to subclasses since it isn’t a property of the class and it isn’t in theprototype(and thus it isn’t inherited by instances of subclasses).Summary:
@uttersis sort of a traditional class variable,headsis a public instance variable with a default value, andfeetis sort of a private class variable.