Wednesday, August 24, 2011

Why Coffeescript's fat arrow makes it more functional (than JS)

We all know that in JS this is not read from the scope chain, it's reset on a context by context basis. Experienced JS programmers work around it and are quite used to it, but I think this fact made JS a lot less beautiful than it should be. Here is a simple example


var Note = Backbone.Model.extend({
initialize: function() {},
delete: function() {
//do something
this.log('deleted');
},
log: function(msg) {
alert(msg);
}
});
var note = new Note();

$('#delete-note').click(function(){
note.delete();
});


Sure, backbone.js already makes things a lot cleaner but the itchy point is this

$('#delete-note').click(function(){
note.delete();
});

The fact that you have to wrap the event handler within a function just make it more like a block passed in than what it really is - a function, especially when you are from a ruby background.
It really should just be

$('#delete-note').click(note.delete);


Well, you can't. If you do that, all the 'this' will be of a different meaning in the body of the delete function - in our example, it will complain that the log is undefined for HTMLElement.
Here is what Coffeescript gives you with its wonderful fat arrow

class Note extends Backbone.Model
delete: =>
#do something
this.log('deleted')
log: (msg) =>
alert(msg)

note = new Note
$('#delete-note').click note.delete

At a glance, it might look like just some keystroke savings. But from my experience the mind set that you can just pass any function as variables around is what makes it a lot more FUNctional.