Im trying to understand why new runs against the function rather than the return of the function in the example y =
:
function returnFunction(){ return function blah(str){ this.x = str; return this;}}
y = new returnFunction()("blah")
// output: Window {x: "blah"; top: Window, window: Window, location: Location, ....}
x = new (returnFunction())("blah")
// output: blah {x: "blah"}
z = new function blah(){return this;}()
// output: blah {}
zz = new function(){return this;}() //note the missing function name
// output: Object {}
b = new function blib(str){this.x = str; return this}
// blib {x: undefined}
bb = new function blib(str){this.x = str; return this}("blah")
// blib {x: "blah"}
c = new function blib(){this.x = "blah"; return this}
// blib {x: "blah"}
So in the case of y new creates a copy of the returnFunction
then invokes it
y = (new returnFunction())()
And by invoking an anonymous function we have no this
so it defaults to Window
.
In the case of x
, by wrapping it in the parens (returnFunction
is invoked returning a the blah
function) and then blah
is invoked by the new operator setting this
to a new object.
It seems odd that I have to wrap new (returnFunction())
to make it execute in the right order.
Could someone explain to me the underlying execution?