我试图理解为什么 new 针对函数运行,而不是示例中函数的返回 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
,通过将其包装在括号中(调用returnFunction
返回blah
函数),然后通过new运算符将this
设置为新对象来调用blah
。
这似乎很奇怪,我必须包装 new (returnFunction())
才能使其以正确的顺序执行。
有人可以向我解释一下底层的执行吗?
最佳答案
new
的优先级高于调用括号 ()
。请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence .
关于javascript - 使用 new 运算符返回 javascript 函数会返回奇数范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28263368/