Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parentheses after "new <function>" optional? [duplicate]

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?

like image 373
Kevin Li Avatar asked Jun 22 '11 11:06

Kevin Li


People also ask

What is the difference between calling function with parentheses and without in JavaScript?

With parenthesis the method is invoked because of the parenthesis, the result of that invocation will be stored in before_add. Without the parenthesis you store a reference (or "pointer" if you will) to the function in the variable.

What does parentheses do in JavaScript?

() (parentheses) They are used to contain a list of parameters passed to functions and control structures and they are used to group expressions to control the order of execution. Some functions have no parameters and in this case, the space between parentheses is blank.

How do you use parentheses in a string in JavaScript?

Given a string that consists of only two types of characters: "(" and ")". We are required to write a function that takes in one such string and balances the parentheses by inserting either a "(" or a ")" as many times as necessary.


2 Answers

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)

like image 159
Marcel Jackwerth Avatar answered Oct 01 '22 08:10

Marcel Jackwerth


Because you can pass parameters like this, eg.

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

Other than that, it is a matter of preference.

like image 40
Gijs Avatar answered Oct 01 '22 09:10

Gijs