我试着去理解对功能为什么新的运行,而不是功能的例子y =
返回:使用new运算符和JavaScript函数的返回返回奇范围
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的情况下, 新创建returnFunction
的副本,然后调用它
y = (new returnFunction())()
并通过调用一个匿名函数我们没有this
所以它默认为Window
。
在x
的情况下,通过在括号包裹它(returnFunction
被调用返回的blah
函数),然后blah
由新的运营商设置到this
一个新的对象被调用。
看起来很奇怪,我必须包装new (returnFunction())
才能使其以正确的顺序执行。
有人可以向我解释底层执行吗?