Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using new operator with return of a javascript function returns odd scope

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?

like image 527
Tomas Harris Avatar asked Oct 20 '22 21:10

Tomas Harris


2 Answers

new has higher precedence than the invocation parens (). See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence.

like image 91
bfavaretto Avatar answered Oct 24 '22 09:10

bfavaretto


It's simply because of operator precedence. new has higher precedence than the function call. Wrapping your function call in parenthesis changes the order of evaluation.

See the precedence table on MDN for more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

like image 23
dee-see Avatar answered Oct 24 '22 09:10

dee-see