Wednesday, January 30, 2013

CoffeeScript prototypes and classes

CoffeeScript tries to overcome the verbosity of JavaScript's prototype and class syntax. Here's how JavaScript does it:

function foo(name){ = name;
} = function(){
    console.log('Status is fubar!');

o = new foo('John');;

That's a bit more of characters to type. If you take a look at how CoffeeScript does it:

foo = (@name) ->                 # the @name is same as writing = name

foo::bar = ->                    # the '::' is the prototype keyword
  console.log 'Status is fubar'
o = new foo('John')


But all this prototype business can be moved into a more object-oriented style using CoffeeScript's class constructs.
class Fish
  constructor: (@name) ->               # gets transformed into a simple JavaScript constructor
  swim: (direction) -> console.log @name + 'is swimming ' + direction # prototype; notice the @name which is
                                                                      # and the direction is a function parameter
fish = new Fish('Nemo')   # play around with fish object

I sort of subscribe to shorter code is cleaner code. That's why I'm liking CoffeeScript so far.