Skip to content

Commit bcf6771

Browse files
committed
Fixed Class Variables recipe
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.
1 parent bbd3725 commit bcf6771

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

chapters/classes_and_objects/class-variables.md

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,22 @@ You want to create a class variable.
99

1010
## Solution
1111

12-
Use json notation in the class body; use `::` to access it outside:
13-
1412
{% highlight coffeescript %}
1513
class Zoo
16-
MAX_ANIMALS: 50
17-
18-
Zoo::MAX_ZOOKEEPERS = 5
14+
@MAX_ANIMALS: 50
15+
MAX_ZOOKEEPERS: 3
1916

20-
Zoo::MAX_ANIMALS
17+
console.log Zoo.MAX_ANIMALS
2118
# => 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
2226
{% endhighlight %}
2327

2428
## Discussion
2529

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

Comments
 (0)