It's because you're relying on Automatic Semicolon Insertion (ASI) (perhaps unintentionally), but also starting a line with a (
. If you correctly terminate the assignment with a ;
, the problem goes away:
function Example() {
this.go();
}
Example.prototype.go = function() {
console.log("going");
}; // <==== ; here
(new Example());
The problem is that without the ;
, the ()
expression following the assignment combines with the function() { }
expression in front of it in a syntactically- (but not logically-) valid way: It calls the function, passing in the result of new Example
. So ASI doesn't kick in.
If you aren't intentionally relying on ASI, just note that assignment expressions need to be terminated with ;
s.
If you are intentionally relying on ASI, you must start lines that have a leading (
or [
with a proactive ;
for this very reason. So in your case:
function Example() {
this.go();
}
Example.prototype.go = function() {
console.log("going");
}
;(new Example());
// ^----