Skip to content

LiveScript Cookbook (Example code)

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.

Solution

Use global <<<:

global <<< require 'ramda'

map (add 1), [2, 3, 4]  # [3, 4, 5]

All you required modules will have it too.