parsing - Why does "new Date().toString()" work given Javascript operator precedence? -


mdn states there 2 operators in javscript share highest precedence:

  • the left-associative member operator: foo.bar
  • the right-associative new operator: new foo()

i explicitly separate two: (new date()).tostring()
see both of them combined: new date().tostring()

according this answer, reason second way works it's second operator's associativity matters when both operators have equal precedence. in case, member operator left associative means new date() evaluated first.

however, if that's case, why new date.tostring() fail? after all, new date just syntactic sugar new date(). above argument says should work, doesn't.

what missing?

the syntax is

memberexpression :     primaryexpression     functionexpression     memberexpression [ expression ]     memberexpression . identifiername     new memberexpression arguments 

new foo().bar cannot parsed new (foo().bar) because foo().bar not memberexpression. moreover, new foo() cannot parsed new (foo()), same reason. conversely, new foo.bar is parsed new (foo.bar) because foo.bar valid memberexpression (an interpretation (new foo).bar impossible because grammar greedy).

that is, precedence rule is: dot beats new, new beats call (parens).

.  -> new -> () 

furthermore, looking directly @ grammar demystifies syntactic sugar turns new foo new foo(). it's newexpression ← new newexpression ← new primaryexpression:

newexpression :     memberexpression     new newexpression 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -