0
foo = new Foo();  // this one I use all the time

vs

foo = new Foo;   // I don't understand what this one does

I've seen some code recently using new Array with now (). Didn't know you could do that. What is the difference and when would I use an un-executed new object?

Fresheyeball
  • 29,567
  • 20
  • 102
  • 164

3 Answers3

1

It means just the very same thing. If you do not specify arguments (parenthesis), it calls the constructor with an empty arguments list. From EcmaScript §11.2.2, The new operator:

The production NewExpression : new NewExpression is evaluated as follows:

  • Return the result of calling the [[Construct]] internal method on constructor, providing no arguments (that is, an empty list of arguments).

The production MemberExpression : new MemberExpression Arguments is evaluated as follows:

  • Let argList be the result of evaluating Arguments, producing an internal list of argument values (11.2.4).
  • Return the result of calling the [[Construct]] internal method on constructor, providing the list argList as the argument values.
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

They both do the same thing, although, from a styling perspective, you should use new Foo(); for readability.

You would also need parenthesis for constructor arguments: new Foo(options);

aaronfay
  • 1,673
  • 1
  • 17
  • 19
1

Both syntax does the same thing. It is purely stylistic issues.

I'd suggest you to stick to one through your code base. Always using the parentheses is the most popular form in the style guides as it is consistent when you pass options.

Simon Boudrias
  • 42,953
  • 16
  • 99
  • 134