I was writing some CoffeeScript just now, and getting a strange error:
TypeError: Thing(param) is not a constructor
But it is! And when I try it in the console:
var that = new Thing(param);
that.doesSomething();
After a bit of confusion, I looked through the compiled source and found out that coffee compiles that = new Thing param to that = new(Thing(param));. Weird; I’ve never seen that before. So I promptly try it: and tada! Now I can replicate:
var that = new(Thing(param));
that.previousLineErrorsOut();
(Incidentally, the CoffeeScript generator on its home page generates the new Thing() form. The plot thickens…)
I also try it out with native constructors (new Worker("somefile") and new(Worker("somefile"))), which behave “correctly”, that is, there’s no difference between the two forms.
So I’m thoroughly confused: what’s new()? Why is it failing in some cases? Why does CoffeeScript transform my perfectly fine new into new()?
newtakes an expression representing a constructor and optionally a list of arguments enclosed in parentheses. For example:When you do this:
It’s trying to run the result of calling
Thingwith the argumentparamas a constructor with no arguments. The parentheses after thenewmakeThing(param)the expression representing the constructor. AsThingdoes not return a constructor in your case, it fails. It’s roughly equivalent to this:I do not know why CoffeeScript transforms it that way.