Skip to content

instance method example for clarification #59

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
instance method example for clarification
  • Loading branch information
Scott Carleton committed Sep 13, 2012
commit b2bcb002bd880d6cea078c693cd9f59cdad2fb2c
20 changes: 20 additions & 0 deletions chapters/classes_and_objects/class-methods-and-instance-methods.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ You want to create a class methods and instance methods.

## Solution

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

### Instance Method
class Songs
_titles: 0 # Although it's directly accessible, the leading _ defines it by convention as private property.

get_count: ->
@_titles

constructor: (@artist, @title) ->
@_titles++

song = new Songs("Rick Astley", "Never Gonna Give You Up")
song.get_count()
# => 1

Songs.get_count()
# => TypeError: Object function Songs(artist, title) ... has no method 'get_count'
{% endhighlight %}


## Discussion

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.