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
punund edited this page Mar 11, 2020
·
2 revisions
Class Methods and Instance Methods
Problem
You want to create class and instance methods.
Solution
Class Method
class Songs
@_titles = 0 # Although it's directly accessible, the leading _ defines it by convention as private property.
@get_count = ->
@@_titles
(@artist, @title) ->
@@._titles++ # Refers to <Classname>._titles, in this case Songs.titles
console.log Songs.get_count()
# => 0
song = new Songs("Rick Astley", "Never Gonna Give You Up")
console.log song
console.log Songs.get_count()
# => 1
#song.get_count()
# => TypeError: Object <Songs> has no method 'get_count'
Instance Method
class Songs
_titles: 0 # Although it's directly accessible, the leading _ defines it by convention as private property.
get_count: ->
@_titles
(@artist, @title) ->
@_titles++
song = new Songs("Rick Astley", "Never Gonna Give You Up")
console.log song.get_count()
# => 1
console.log song
#console.log Songs.get_count()
# => TypeError: Object function Songs(artist, title) ... has no method 'get_count'
Problem
You wan to import a package into global namespace.