Given the following coffeescript code:
class Animal
constructor: (@name) ->
speak: (things) -> "My name is #{@name} and I like #{things}"
This is generated:
var Animal = (function() {
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function(things) {
return "My name is " + this.name + " and I like " + things;
};
return Animal;
})();
But why isn’t this more idiomatic code generated?
var Animal = function Animal(name) {
this.name = name;
};
Animal.prototype.speak = function(things) {
return "My name is " + this.name + " and I like " + things;
};
I know that coffeescript wraps a lot of stuff in anonymous functions to control scope leak, but what could leak here?
The generated code makes it possible to reliably have named functions in Internet Explorer. (In this case, “Animal”.) If you simply use a named function at top-level scope, it will conflict with any
var Animal =declarations that might be present … even in lower scopes, preventing them from being referenced correctly. To work around the IE bug, we include the function wrapper around the class definition.