Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

instance method example for clarification

  • Loading branch information...
commit b2bcb002bd880d6cea078c693cd9f59cdad2fb2c 1 parent 4c42df5
@ScotterC ScotterC authored
Showing with 20 additions and 0 deletions.
  1. +20 −0 chapters/classes_and_objects/class-methods-and-instance-methods.md
View
20 chapters/classes_and_objects/class-methods-and-instance-methods.md
@@ -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.
@@ -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.
Please sign in to comment.
Something went wrong with that request. Please try again.