You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The recipe mixed up class variables and instance variables, so it was just the other way round.
From http://coffeescript.org/#classes
> Finally, class definitions are blocks of executable code, which make for interesting metaprogramming possibilities. Because in the context of a class definition, this is the class object itself (the constructor function), you can assign static properties by using
> `@property: value`, and call functions defined in parent classes: `@attr 'title', type: 'text'`
Also added a case for an instance variable to better distinguish between the two.
Copy file name to clipboardExpand all lines: chapters/classes_and_objects/class-variables.md
+11-7Lines changed: 11 additions & 7 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -9,18 +9,22 @@ You want to create a class variable.
9
9
10
10
## Solution
11
11
12
-
Use json notation in the class body; use `::` to access it outside:
13
-
14
12
{% highlight coffeescript %}
15
13
class Zoo
16
-
MAX_ANIMALS: 50
17
-
18
-
Zoo::MAX_ZOOKEEPERS = 5
14
+
@MAX_ANIMALS: 50
15
+
MAX_ZOOKEEPERS: 3
19
16
20
-
Zoo::MAX_ANIMALS
17
+
console.log Zoo.MAX_ANIMALS
21
18
# => 50
19
+
20
+
console.log Zoo.MAX_ZOOKEEPERS
21
+
# => undefined (it is an instance variable)
22
+
23
+
zoo = new Zoo
24
+
console.log zoo.MAX_ZOOKEEPERS
25
+
# => 3
22
26
{% endhighlight %}
23
27
24
28
## Discussion
25
29
26
-
Coffeescript will store these values on the class prototype (e.g. Zoo.prototype.MAX_ANIMALS) rather than on individual object instances, which conserves memory and gives a central location to store class-level values.
30
+
Coffeescript will store these values on the object itself rather than on the object prototype (and thus on individual object instances), which conserves memory and gives a central location to store class-level values.
0 commit comments