为什么“new Date()。toString()”给出Javascript运算符优先级的工作? [英] Why does "new Date().toString()" work given Javascript operator precedence?

查看:77
本文介绍了为什么“new Date()。toString()”给出Javascript运算符优先级的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MDN声明 Javscript中具有最高优先级的两个运算符:

MDN states that there are two operators in Javscript that share the highest precedence:


  • 左关联成员运算符: foo.bar

  • 右关联新运算符: new Foo()

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

我通常明确地将两者分开:(new Date())。toString()

但我经常看到它们两者合并: new Date()。toString()

I usually explicitly separate the two: (new Date()).toString()
But I frequently see both of them combined: new Date().toString()

根据这个答案,第二种方式的原因是它是当两个运算符具有相同的优先级时,第二个运算符的关联性很重要。在这种情况下,成员运算符是左关联的,这意味着首先计算 new Date()

According to this answer, the reason the second way works is that it's the second operator's associativity that matters when both operators have equal precedence. In this case, the member operator is left associative which means new Date() is evaluated first.

但是,如果是这样的话,为什么 new Date.toString()会失败?毕竟,新日期只是语法糖 for new Date()。上面的论点说它应该有效,但显然不行。

However, if that's the case, then why does new Date.toString() fail? After all, new Date is just syntactic sugar for new Date(). The above argument says it should work, but it obviously doesn't.

我缺少什么?

推荐答案

语法

MemberExpression :
    PrimaryExpression
    FunctionExpression
    MemberExpression [ Expression ]
    MemberExpression . IdentifierName
    new MemberExpression Arguments

new foo()。bar 无法解析为 new(foo()。bar)因为 foo()。bar 不是会员表达。此外,出于同样的原因, new foo()无法解析为 new(foo())。相反, new foo.bar 解析为 new(foo.bar)因为 foo.bar 是一个有效的MemberExpression(解释(new foo).bar 是不可能的,因为语法是贪婪的)。

new foo().bar cannot be parsed as new (foo().bar) because foo().bar is not a MemberExpression. Moreover, new foo() cannot be parsed as new (foo()), for the same reason. Conversely, new foo.bar is parsed as new (foo.bar) because foo.bar is a valid MemberExpression (an interpretation (new foo).bar is impossible because the grammar is greedy).

也就是说,优先规则是:dot beats new,new beats call(parens)。

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

.  -> new -> ()

此外,直接查看语法揭开了转向的语法糖新的Foo 进入新的Foo()。它只是NewExpression←new NewExpression←new PrimaryExpression:

Furthermore, looking directly at the grammar demystifies the syntactic sugar that turns new Foo into new Foo(). It's simply NewExpression ← new NewExpression ← new PrimaryExpression:

NewExpression :
    MemberExpression
    new NewExpression

这篇关于为什么“new Date()。toString()”给出Javascript运算符优先级的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆