- First, you need to know what is IIFE(immediately invoked function expression).
IIFE is as name suggested you can call a function immediately after declared. But JS parser should see whole as one expression.
Ex.
(function(){console.log("foo")}())
!function(){console.log("foo")}()
+function(){console.log("foo")}()
All these forces parser to see function(){console.log("foo")}()
side of it as complete expression so it can call immediately.
- Second, how
new (Foo.bar())()
works.
When you use new (Foo.bar())()
in first parentheses returns this
which is Foo
itself. Because bar
method is returning Foo
. After second parentheses()
calls it(Foo) and then new
is creates a new instance of Foo
. Basically you are writing new Foo()
with using IIEF.
- Third why
new Foo.bar()()
throws error.
When JS parser sees the expression new Foo.bar()
it is immediately try creates an instance if Foo.bar
and Foo.bar
is not a constructor. After that JS throws that error.
But if parser sees ()
it could throw another error that Uncaught SyntaxError: Unexpected token ')'
. Because JS can not understand the what is left from that line, ()
.
Difference between
new Foo.bar()()
and new (Foo.bar())()
same as
function(){console.log("foo")}()
and (function(){console.log("foo")})()
it throws different error and stop parsing, because Foo.bar
is not a constructor to call.
I hope it helps.
Some links to understand.
What does the exclamation mark do before the function?