[英]JavaScript: Why does my `new` need parens?
I wanted to instantiate a constructor that was returned by a function, but noticed that new
was a little quirky about it: 我想实例化一个函数返回的构造函数,但注意到new
有点古怪:
// 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}
Why are the parens needed? 为什么需要括号?
In the first case new
invokes getConstructor
function as a "constructor" for an object. 在第一种情况下, new
调用getConstructor
函数作为对象的“构造函数”。 That function returns another function (you've set it explicitly) - that's why function X(){this.x=true}
is the output. 该函数返回另一个函数(您已对其进行了显式设置)–这就是为什么function X(){this.x=true}
是输出的原因。
In the second case parens make the new
keyword invoke the function, that was returned from getConstructor
execution. 在第二种情况下,parens使new
关键字调用该函数,该关键字是从getConstructor
执行返回的 。
For better understanding: 为了更好的理解:
function getConstructor(){ return function X(){this.x=true} }
var func = getConstructor(); //=> function X(){this.x=true}
var instance = new func(); //=> X {x: true}
Because new
operator has higher precedence than function call
operator. 因为new
运算符比function call
运算符具有更高的优先级 。
If you want the constructor function returned by getConstructor
, you have to wrap it to have the function call execute first. 如果希望getConstructor
返回构造函数,则必须对其进行包装以使函数调用首先执行。
Check the Javascript Operator Precedence . 检查Javascript运算符的优先级 。
Without the parens, it looks like getConstructor is itself a constructor. 没有括号,看起来getConstructor本身就是一个构造函数。 Remember, new Something()
attempts to create an object with the constructor Something
(for example. new String()
). 请记住, new Something()
尝试使用构造函数Something
创建对象(例如new String()
)。 But you want your constructor to be the function returned to getConstructor(), so you need parens to make the call to getConstructor() parse as a lone function call rather than as the operand of new
. 但是,您希望构造函数是返回给getConstructor()的函数,因此需要parens使对getConstructor()的调用解析为一个单独的函数调用,而不是作为new
的操作数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.