Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript class methods and instance methods


May 09, 2021 CoffeeScript


Table of contents


Class methods and instance methods

Problem

The method you want to create classes and instances.

Solution

Class 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) ->
    @constructor._titles++     # Refers to <Classname>._titles, in this case Songs.titles

Songs.get_count()
# => 0

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

song.get_count()
# => TypeError: Object <Songs> has no method 'get_count'

The 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'

Discuss

Coffeescript saves class methods (also known as static methods) in the object itself, rather than in object prototypes (and a single instance of an object), and saves class-level variables at the center while saving records.