我试图理解为什么新的运行反对函数而不是示例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"}
所以在y new的情况下会创建returnFunction
的副本然后调用它
y = (new returnFunction())()
通过调用匿名函数,我们没有this
,因此默认为Window
。
对于x
,通过将其包装在parens中(returnFunction
被调用,返回blah
函数),然后blah
由新运算符调用将this
设置为新对象。
我必须包装new (returnFunction())
以使其以正确的顺序执行,这似乎很奇怪。
有人可以向我解释底层执行吗?
答案 0 :(得分:2)
new
的优先级高于调用parens ()
。请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence。
答案 1 :(得分:1)
这仅仅是因为运营商的优先权。 new
的优先级高于函数调用。在括号中包含函数调用会更改评估顺序。
有关详细信息,请参阅MDN上的优先级表:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence