Why would you invoke new Date without parentheses?

2020-06-01 08:14发布

问题:

I have just seen this snippet while accidentally opening dev tools in Gmail:

var GM_TIMING_END_CHUNK1=(new Date).getTime();

I would usually expect something like this, as it's rather uncommon to invoke a constructor without parentheses (at least I have never seen it until now):

var GM_TIMING_END_CHUNK1=new Date().getTime();

or

var GM_TIMING_END_CHUNK1=Date.now(); //newer browsers

Is there any advantage in doing so, any difference in behavior? It's the exact same amount of characters needed, so brevity won't be a reason.

回答1:

You can invoke constructors in JS w/o the parenthesis if no parameters are to be passed, the effect is the same.

new Date() vs new Date the same.

However, it makes a difference when you want to call a method on the resulting object:

new Date().getTime() works but new Date.getTime() would not because in the latter case the interpreter assumes getTime is a method of the Date type but that's not true, getTime is an instance method - only exists in constructed objects. To overcome this you can wrap parenthesis around the constructor call to tell the interpreter that it is an expression:

(new Date).getTime()

This way first the expression is evaluated and getTime is called on the result which is an instance of Date.



回答2:

In addition to the existing comments about optional parentheses -- i.e. new Date() <==> new Date -- note also that Date.now is a static method. That is, no Date object is ever instantiated. The method is a property of the Date constructor itself. In this way, it is different than the other two examples.

As a matter of style, I prefer including all optional parens for consistency and clarity:

(new Date()).getTime()


回答3:

When a function is used as an object constructor and no arguments are being passed, the parentheses are optional. d = new Date; means the same thing as d = new Date();.



回答4:

There is no difference in both statements, parenthesis are optional, So usually programmers drop it.

In your second example:

new Date().getTime();

one of good practice programmers follow to wrap object in parenthesis before calling function or property. so it will be:

(new Date()).getTime();

as discussed above object parenthesis are optional. So shorter cleaner code is:

(new Date).getTime();


回答5:

You might want to have a look at this answer: Can we omit parentheses when creating an object using the "new" operator?

Basicly new Date is equivilent to writing new Date() though you might prefer to use new Date() for consistency, since functions and constructors are so similar in JavaScript and the parentheses-less syntax is definitely illegal for function invocation.