5

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?

4

2 回答 2

2

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

于 2013-11-05T02:08:15.840 回答
1

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

于 2013-11-05T02:09:46.000 回答