15

I have run the following pair of code snippets in Chrome console, with the same results:

test = new function(){
  var a = 1;
  var b = 2;
  var c = 3;
  this.debugBase = function(){console.log('' + a + b + c)};
};
test
debugBase: function (){console.log('' + a + b + c)}
__proto__: Object

Versus:

test2 = new (function(){
  var a = 1;
  var b = 2;
  var c = 3;
  this.debugBase = function(){console.log('' + a + b + c)};
})();
test2
debugBase: function (){console.log('' + a + b + c)}
__proto__: Object

Am I missing something? Is there any significance to the parentheses after the function? If not, why do people put them there?

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
Kevin Li
  • 1,540
  • 2
  • 17
  • 23

3 Answers3

14

A similar questions was asked here: new MyClass() vs. new MyClass. The complete and accepted answer by Daniel Vassallo:

Quoting David Flanagan1:

As a special case, for the new operator only, JavaScript simplifies the grammar by allowing the parenthesis to be omitted if there are no arguments in the function call. Here are some examples using the new operator:

o = new Object;  // Optional parenthesis omitted here
d = new Date();  

Personally, I always use the parenthesis, even when the constructor takes no arguments.

In addition, JSLint may hurt your feelings if you omit the parenthesis. It reports Missing '()' invoking a constructor, and there doesn't seem to be an option for the tool to tolerate parenthesis omission.


1 David Flanagan: JavaScript the Definitive Guide: 4th Edition (page 75)

Community
  • 1
  • 1
Marcel Jackwerth
  • 53,948
  • 9
  • 74
  • 88
3

Because you can pass parameters like this, eg.

var x = new String(5); // '5'

Other than that, it is a matter of preference.

Gijs
  • 5,201
  • 1
  • 27
  • 42
0

putting the parantheses actually runs the function. Without them, the function is just defined.

EDIT: I didn't notice the "new" keyword you used. Your function is called in either case. You don't generally need the new keyword here though. In the example you've given, they are essentially the same, the parentheses at the end are redundant.

See this jsfiddle for what I mean ( http://jsfiddle.net/Gs2jH/ ).

If you run it, you'll see that only the 2nd item is called.

Gerrat
  • 28,863
  • 9
  • 73
  • 101