block by joyrexus 5995940

Simple example of class & instance variables and fat arrow usage.

CoffeeScript Classes

A simple example demonstrating use of static & instance variables and the fat arrow (=>).

Static vs Instance Variables

CS stores static properties and methods on the class itself, not on the prototype. Hence, class variables do not conflict with identically named instance variables.


class Greet

  @p: 'class/static property'
  @hi: -> 
    '''class/static method'''
    print "Hi there #{@name}!"

  constructor: (@name) ->

  p: 'instance property'
  hi: -> 
    '''instance method'''
    print "Hi there #{@name}!"

  bye: => print "Goodbye #{@name}!"


greet = new Greet 'Bob'

Greet.hi()          # Hi there Greet!
greet.hi()          # Hi there Bob!

print Greet.name    # Greet
print greet.name    # Bob

print Greet.p       # class property
print greet.p       # instance property 

Fat Arrow

Methods declared with the fat arrow will be automatically bound to each instance of the class when the instance is constructed. As a result, functions created with the fat arrow are able to access properties of the this (@) where they’re defined, whatever the context in which they’re invoked.


class Context extends Greet
  invoke: (f) -> f()

context = new Context 'Joe'

context.bye()             # Goodbye Joe!
context.invoke greet.bye  # Goodbye Bob!

Reference

Official Docs

Little Book

Cookbook

classes.coffee