2014-03-12 45 views
0

我想实例,是由一个函数返回一个构造函数,但是注意的是new是一个有点古怪一下:JavaScript:为什么我的`new`需要parens?

// This function returns a constructor function 
function getConstructor(){ return function X(){this.x=true} } 

getConstructor();  //=> function X(){this.x=true} 
new getConstructor(); //=> function X(){this.x=true} 

new (getConstructor()); //=> X {x: true} 

为什么在括号需要的?

回答

3

在第一种情况new调用getConstructor功能作为一个“构造”的对象。该函数返回另一个函数(您已明确设置) - 这就是为什么function X(){this.x=true}是输出。

在第二种情况下,parens使new关键字调用函数,即getConstructor执行返回

为了更好地理解:

function getConstructor(){ return function X(){this.x=true} } 

var func = getConstructor();  //=> function X(){this.x=true} 
var instance = new func(); //=> X {x: true} 
+0

'新新新功能(){返回功能(){返回函数I(){this.cannot = '偶数'}}}'谢谢:d – ChaseMoskal

2

因为new操作员更高的优先级比操作function call

如果你想在构造函数的返回getConstructor,你必须把它包起来有函数调用执行第一。

检查Javascript Operator Precedence

0

如果没有括号,它看起来像getConstructor本身就是一个构造函数。请记住,new Something()尝试创建与构造Something的对象(例如,new String())。但是,你希望你的构造函数是)返回到getConstructor(函数,所以你需要括号拨打电话到getConstructor()解析为一个孤独的函数调用,而不是为new操作数。

相关问题