5

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.

Community
  • 1
  • 1
nrabinowitz
  • 55,314
  • 10
  • 149
  • 165

3 Answers3

4

if

var MyFunction = function(){
    alert("ok");
}

then

var myVar = new(MyFunction);

becomes

var myVar = new(function(){
    alert("ok");
});

It is just a matter of organizing code.

Diode
  • 24,570
  • 8
  • 40
  • 51
4

They 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
maerics
  • 151,642
  • 46
  • 269
  • 291
  • Yeah, this was pretty much what I was guessing. Thanks for breaking down the various options - still trying to figure out why `new(Foo)` would be a good stylistic choice. – nrabinowitz Mar 27 '12 at 17:16
  • @nrabinowitz: well, I suppose there's no accounting for taste =) – maerics Mar 27 '12 at 17:24
3

The example you made is equivalent, there is no differences: the new is an operator. It's not uncommon 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.

ZER0
  • 24,846
  • 5
  • 51
  • 54