admin管理员组文章数量:1327308
I'm looking through the Vows documentation and in several places it uses the syntax
var myVar = new(MyFunction);
e.g.
var promise = new(events.EventEmitter);
I am familiar with new MyFunction()
and new MyFunction
(and yes, I have read this question). But the syntax above is, well, new to me - it looks like a function call, though I suspect it's just new MyFunction
with some added parentheses. Is there any difference between these ways of using new
? If not, is there any good argument for using one or the other? I would have thought new MyFunction()
was the most legible.
Apologies if this is a duplicate - I searched but couldn't find it.
I'm looking through the Vows documentation and in several places it uses the syntax
var myVar = new(MyFunction);
e.g.
var promise = new(events.EventEmitter);
I am familiar with new MyFunction()
and new MyFunction
(and yes, I have read this question). But the syntax above is, well, new to me - it looks like a function call, though I suspect it's just new MyFunction
with some added parentheses. Is there any difference between these ways of using new
? If not, is there any good argument for using one or the other? I would have thought new MyFunction()
was the most legible.
Apologies if this is a duplicate - I searched but couldn't find it.
Share Improve this question edited May 23, 2017 at 12:16 CommunityBot 11 silver badge asked Mar 27, 2012 at 4:45 nrabinowitznrabinowitz 55.7k10 gold badges151 silver badges169 bronze badges3 Answers
Reset to default 4They appear to be the same, just with parentheses in different places, perhaps stylistically or for clarity to the author(s). The following are all identical:
function Foo() { this.now = new Date(); }
var f1 = new Foo;
var f2 = (new Foo);
var f3 = new(Foo);
var f4 = new Foo();
var f5 = (new Foo());
Note that the form below is different because the "Foo" function is called directly (due to the precedence of the parens), returning nothing (undefined), which is an invalid argument to the "new" operator (because "undefined" is not a function):
var x = new(Foo()); // TypeError: undefined is not a function
if
var MyFunction = function(){
alert("ok");
}
then
var myVar = new(MyFunction);
bees
var myVar = new(function(){
alert("ok");
});
It is just a matter of organizing code.
The example you made is equivalent, there is no differences: the new
is an operator. It's not unmon find parenthesis around operators like:
if (typeof(myvar) === "function")
or also:
return(myvar);
But they are operators, parenthesis are not needed. I don't like them in these contexts, but it's a matter of personal preferences.
本文标签: javascriptnew MyFunction() vs new(MyFunction)Stack Overflow
版权声明:本文标题:javascript - new MyFunction() vs. new(MyFunction) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742203530a2432394.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论