2013-11-05 54 views
5

我试着去理解对功能为什么新的运行,而不是功能的例子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())才能使其以正确的顺序执行。

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

回答