I’ve just ran across Coffeescript… can’t believe what sort of a hole I’ve been living in.
It’s a source to source compiler (ie when you 'compile' a coffeescript script, you get javascript source.)
So why would you want a source to source compiler for Javascript? Well, as apps become more and more 'front-end' heavy with DHTML/Ajax bling bling, the javascript that holds all that together also becomes more and more complex. Yeah, sure you used Jquery (or 'insert your favourite js framework') - but that’s not even scratching the surface. You’re still writing tons of js code, and dealing with its idiosyncracies and tearing your hair apart.
Enter Coffeescript - clean syntax with elements of style borrowed from ruby and python, this is super clean and efficient. You write your code in coffeescript which is neat, clean and concise. What it generates is very idiomatic and clean javascript.
Let’s try something - take a guess at what the following does:
var Animal, Mammal, animal, farm, _i, _len,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Animal = (function() {
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
return console.log("I am a " + this.name);
};
return Animal;
})();
Mammal = (function(_super) {
__extends(Mammal, _super);
function Mammal() {
return Mammal.__super__.constructor.apply(this, arguments);
}
Mammal.prototype.speak = function() {
Mammal.__super__.speak.apply(this, arguments);
return console.log("and I'm a mammal");
};
return Mammal;
})(Animal);
farm = [new Animal("fish"), new Mammal("dog")];
for (_i = 0, _len = farm.length; _i < _len; _i++) {
animal = farm[_i];
animal.speak();
}
And now - see if you like this better:
class Animal
constructor: (@name)->
speak: ->
console.log "I am a #{@name}"
class Mammal extends Animal
speak:->
super
console.log ("and I'm a mammal")
farm=[ (new Animal "fish"), (new Mammal "dog")]
animal.speak() for animal in farm
The javascript version is the generated from the coffeescript version above . Head over to coffeescript.org page - they have an online interpreter where you can try out coffeescript code and it generates equivalent javascript source.
If you’re wow’ed with that (I am) - and just in case you’re saying good bye to javascript, here’s the nub.. since its a source to source compiler, unless you understand what’s going on under the covers, you’ll hit a problem soonish when you have to debug something.
So, Javascript isn’t optional - but if you have that bit covered, there’s no reason to have to 'live' with the iffy side of javascript. Take a look something like coffeescript and have a little fun along the way.