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){
    this.name = name;
}

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

o = new foo('John');
o.bar();

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 this.name = name

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

console.log o.name
o.bar()

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 this.name
                                                                      # and the direction is a function parameter
  
fish = new Fish('Nemo')   # play around with fish object
console.log fish.name
fish.swim('north')

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