使用返回javascript函数的new运算符返回奇数范围

时间:2013-11-05 01:58:05

标签: javascript new-operator

我试图理解为什么新的运行反对函数而不是示例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())以使其以正确的顺序执行,这似乎很奇怪。

有人可以向我解释底层执行吗?

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:1)

这仅仅是因为运营商的优先权。 new的优先级高于函数调用。在括号中包含函数调用会更改评估顺序。

有关详细信息,请参阅MDN上的优先级表:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence