What is the correct Javascript operator precedence

2020-07-17 16:34发布

问题:

If I run the following code on Firefox I get an error:

new Number.toString;

But according to MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence new Number should evaluate first. So the table is not correct I think.

Let us take a look at MSDN: http://msdn.microsoft.com/en-us/library/z3ks45k7(v=vs.94).aspx . Above the table is written that operators are evaluated from left to right. But:

a=1;
b=a=2;

Now b has the value 2 which suggest evaluation from right to left. So also this precedence table is not correct.

Can anyone give me a correct table?

回答1:

according to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence$revision/510297#Table new Number should evaluate first. So the table is not correct I think.

The new Operator is complicated. Let's check the official language grammar: It does occur in two manifestations:

MemberExpression := new MemberExpression Arguments | …
NewExpression := new NewExpression | …

The latter, where is called without arguments, does indeed have a lesser precedence than the property accessors - so that your expression evaluates as new (Number.toString). However, when new is called with arguments (parenthesis), then it does have a greater precedence than a CallExpression and is equal to a property accessor, in which case they'd evaluate left-to-right. Indeed, the MDN table should make this more clear.

Let us take a look at MSDN: http://msdn.microsoft.com/en-us/library/z3ks45k7(v=vs.94).aspx . Above the table is written that operators are evaluated from left to right.

This is definitely wrong. Operator associativity is not always left-to-right, most obvious at the assignment operators as in your example. The MDN table states this correct. Also, MSDN seems to oversimplify the precedence of postfix operators.

Can anyone give me a correct table?

Try my new revision of MDN's table.



回答2:

Here is MDN's full operator precedence table, available at your link: