The first returns a link to the newly created instance of your anonymous constructor function (= this ).
The second returns the return value of the anonymous function. Since your function does not have a return statement, it will implicitly return undefined.
Try the following:
var t1 = new function(obj) { console.log(obj); }(extObj); var t2 = (function(obj) { console.log(obj); })(extObj); typeof t1 => "object" typeof t2 => "undefined"
(Btw, t1.constructor will return the original function you created t1 s.)
The difference becomes much clearer if you add a return statement:
var t1 = new function(obj){ return(obj); }("foo"); var t2 = (function(obj){ return(obj); })("bar"); console.log(t1) => "object" console.log(t2) => "bar"
IMO, this makes (function)() much more useful for everyday usecase - you assign the return value of the execution of this function to a variable, which will usually be what you want if you work with immediately called functions. Especially when you have more complex things like (pseudocode):
var myNameSpace = (function(){ ... return{ functionX, variable1, variable2 } }();
Basically, you can use an arbitrary unary operator to turn a function declaration into an expression that is immediately called. Therefore, you can also write:
!function(){ }(); ~function(){ }(); -function(){ }(); +function(){ }();
depending on the return statement of your function, this will give different return results. ! - negate returnvalue +|- evaluate as Number (apply a negative sign) ~ apply bitwise not to the return value.
source share