I have been using coffeescript classes, and as far as I was aware, functions should always return the last statement automatically. I am finding however, that functions defined in the constructor object, are not returning anything by default. Why is this?
CoffeeScript
constructor: ->
@ # <~~ returned as expected
class MyClass
constructor: ->
@ # <~~ not returned - why?
class MyClass
constructor: ->
return ->
@ # <~~ returned like normal!
JavaScript
var MyClass;
({
constructor: function() {
return this;
}
});
MyClass = (function() {
function MyClass() {
this;
}
return MyClass;
})();
MyClass = (function() {
function MyClass() {
return function() {
return this;
};
}
return MyClass;
})();
The “constructor” method is called when you use the “new” keyword on a class – therefore the return value is always supposed to be the new instance, not some other value that you’d like to return. However, it seems like CoffeeScripts lets you force a different return value via the “return” keyword.
When you name a normal function “constructor” (not a method = outside of a class definition), it’s not a constructor but a regular function and therefore returns as expected.