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?
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.
() (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.
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.
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 thenew
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)
Because you can pass parameters like this, eg.
var x = new String(5); // '5'
Other than that, it is a matter of preference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With