In CoffeeScript, this:
class Foo
method: (x) ->
x+1
Compiles to:
// Generated By CoffeeScript
Foo = (function() {
function Foo() {}
Foo.prototype.method = function(x) {
return x+1;
}
return Foo;
})()
Which seems a bit excessive. The following should be functionally identical:
// Generated by Dave
function Foo() {}
Foo.prototype.method = function(x) {
return x+1;
}
What is the motivation for the extra “closure” wrapper?
This is not merely an idle question of styling; it has implication to overall code size.
The Coffee version minifies into 84 bytes:
Foo=function(){function e(){}return e.prototype.method=function(e){return e+1},e}();
My version minifies into only 61 bytes:
function Foo(){}Foo.prototype.method=function(e){return e+1};
23 bytes is silly kinds of irrelevant, but in a project with many many classes, overhead begins to add up.
Ok, I wrote an answer below refuting the byte size theory … for any reasonable class, the Coffee method is going to be smaller.
There’s probably other reasons too. Help me think of them.
Jeremy answers this over in a related question – it looks like the primary intent is to avoid triggering an IE bug.