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

风格不统一 提交于 2020-01-21 11:38:06

问题


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?


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/19780725/using-new-operator-with-return-of-a-javascript-function-returns-odd-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!