Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you invoke new Date without parentheses? [duplicate]

Tags:

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.

like image 784
m90 Avatar asked Jan 13 '14 19:01

m90


People also ask

What happens when a method is accessed without the () parentheses?

When we call a function with parentheses, the function gets execute and returns the result to the callable. In another case, when we call a function without parentheses, a function reference is sent to the callable rather than executing the function itself.

Why do some methods not have parentheses?

Without parentheses you're not actually calling the function. A function name without the parentheses is a reference to the function. We don't use the parentheses in that code because we don't want the function to be called at the point where that code is encountered.

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.

Can you call a function without parentheses JavaScript?

Calling a JavaScript function without the parens passes that function's definition as a reference. It is one of the fundamentals to programming in JavaScript known as callbacks.


1 Answers

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.

like image 152
marekful Avatar answered Sep 29 '22 07:09

marekful