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.
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.
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.
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.
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.
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.
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