What is the correct Javascript operator precedence table?

爷,独闯天下 提交于 2019-12-19 03:45:11

问题


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:



来源:https://stackoverflow.com/questions/21158960/what-is-the-correct-javascript-operator-precedence-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!