Why are the operators in the expression new Date (). Do getTime () apply in strict order from left to right?

The following expression seems to work as intended and returns the current timestamp.

new Date().getTime() 

However, I cannot understand why the operators are applied in strict order from left to right.

MDN says the member ( . ) Operator has higher priority than new . That would mean that . should apply before new . Thus, the expression should be evaluated as:

 new (Date().getTime()) 

But in fact, it is rated as:

 (new Date()).getTime() 

I suppose there must be something that I missed, but I do not understand that.

Note. I do not use this expression (I prefer the Date.now() method). This is just my curiosity.

+6
source share
1 answer

The MDN priority table is not entirely correct; the new operator and property access operators are part of the non-terminal MemberExpression in the grammar. Since they are left-associative operators,

 new something.something 

estimated as

 (new something).something 

Here is the relevant part of the specification.

Therefore, in your approximate expression

 new Date().getTime() 

whole left side . parsed as an expression of MemberExpression. What is this expression of MemberExpression? This is a new MemberExpression production, so it’s deeper in the parsing tree and gives us left-associative behavior.

edit is something else I was just thinking about. Let them say that we have an object:

 var obj = { findConstructor: function(name) { return window[name]; } }; 

Now try this expression to get the time using this object:

 new obj.findConstructor("Date")().getTime() 

This will give you an error. (I'm here on thin ice :) This is because he analyzes it as

 new (obj.findConstructor("Date")().getTime)() 

which obviously won't work. Instead, you need to add explicit brackets:

 (new obj.findConstructor("Date")()).getTime() 
+7
source

All Articles