使用返回javascript函数的new运算符返回奇数范围 [英] Using new operator with return of a javascript function returns odd scope
问题描述
我试图理解为什么新的运行对抗函数而不是示例中的函数返回 y =
:
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"}
所以在这种情况下y new 创建 returnFunction
的副本然后调用它
So in the case of y new creates a copy of the returnFunction
then invokes it
y = (new returnFunction())()
并且通过调用匿名函数我们没有这个
所以它默认为 Window
。
And by invoking an anonymous function we have no this
so it defaults to Window
.
在 x
的情况下,通过将其包装在parens中( returnFunction
被调用,返回 blah
function)然后 blah
由新的运算符设置调用
一个新的对象。
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.
我必须包装 new(returnFunction())
来制作它以正确的顺序执行。
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?
推荐答案
new
的优先级高于调用parens ()
。请参阅 https://developer.mozilla.org/en- US / docs / Web / JavaScript / Reference / Operators / Operator_Precedence 。
new
has higher precedence than the invocation parens ()
. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence.
这篇关于使用返回javascript函数的new运算符返回奇数范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!