Skip to content

Commit b2bcb00

Browse files
author
Scott Carleton
committed
instance method example for clarification
1 parent 4c42df5 commit b2bcb00

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

chapters/classes_and_objects/class-methods-and-instance-methods.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ You want to create a class methods and instance methods.
99

1010
## Solution
1111

12+
### Class Method
1213
{% highlight coffeescript %}
1314
class Songs
1415
@_titles: 0 # Although it's directly accessible, the leading _ defines it by convention as private property.
@@ -30,6 +31,25 @@ song.get_count()
3031
# => TypeError: Object #<Songs> has no method 'get_count'
3132
{% endhighlight %}
3233

34+
### Instance Method
35+
class Songs
36+
_titles: 0 # Although it's directly accessible, the leading _ defines it by convention as private property.
37+
38+
get_count: ->
39+
@_titles
40+
41+
constructor: (@artist, @title) ->
42+
@_titles++
43+
44+
song = new Songs("Rick Astley", "Never Gonna Give You Up")
45+
song.get_count()
46+
# => 1
47+
48+
Songs.get_count()
49+
# => TypeError: Object function Songs(artist, title) ... has no method 'get_count'
50+
{% endhighlight %}
51+
52+
3353
## Discussion
3454

3555
Coffeescript will store class methods (also called static methods) 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)