简写属性名称*this*

app*_*ple 18 javascript language-lawyer ecmascript-6

以下代码失败

为什么我不能用这个简写属性名?


来自浏览器的错误消息

chrome 66.0.3359.117:未捕获的SyntaxError:意外的标记}

firefox 59.0.1:这是一个无效的标识符

edge 41.16299.371.0:标识符的关键字使用无效

我不太了解这些消息所说的内容.


为了说清楚,下面的代码运行正常

let x = 5
let y = {x}
let z = {this:this}

console.log({x,y,z})
Run Code Online (Sandbox Code Playgroud)

ein*_*nus 16

根据ECMA规范(我粗略地提出了重要的内容):

12.2.6对象初始化器

NOTE 1 An object initializer is an expression describing the initialization of an Object, written in a form resembling a literal. It is a list of zero or more pairs of property keys and associated values, enclosed in curly brackets. The values need not be literals; they are evaluated each time the object initializer is evaluated.

句法

  • ObjectLiteral [收益率]:
    • {}
    • {PropertyDefinitionList [?yield]}
    • {PropertyDefinitionList [?yield],}
  • PropertyDefinitionList [Yield]:
    • PropertyDefinition [?产量]
    • PropertyDefinitionList [?Yield],PropertyDefinition [?Yield]
  • PropertyDefinition [收益率]:
    • IdentifierReference [?产量]
    • CoverInitializedName [?产量]
    • PropertyName [?Yield]:AssignmentExpression [In,?Yield]
    • MethodDefinition [?产量]
  • PropertyName [收益率]:
    • LiteralPropertyName
    • ComputedPropertyName [?产量]
  • LiteralPropertyName:
    • IdentifierName
    • 字符串字面量
    • NumericLiteral
  • ComputedPropertyName [Yield]: - [AssignmentExpression [In,?Yield]]
    • CoverInitializedName [收益率]:
    • IdentifierReference [?Yield] Initializer [In,?Yield]
  • 初始化器[In,Yield]:
    • = AssignmentExpression [?In,?Yield]

NOTE 2 MethodDefinition is defined in 14.3.

NOTE 3 In certain contexts, ObjectLiteral is used as a cover grammar for a more restricted secondary grammar. The CoverInitializedName production is necessary to fully cover these secondary grammars. However, use of this production results in an early Syntax Error in normal contexts where an actual ObjectLiteral is expected.


12.1标识符

句法

  • IdentifierReference [收益率]:
    • 识别码
    • [〜收益率]收益率
  • BindingIdentifier [收益率]:
    • 识别码
    • [〜收益率]收益率
  • LabelIdentifier [收益率]:
    • 识别码
    • [〜收益率]收益率
  • 标识符:
    • IdentifierName 但不是ReservedWord

这意味着在简写中,let x = {标识符}不允许保留字作为标识符.并且this是一个保留字,请查看11.6.2保留字及以后.在另一方面,我们看到,写它的扩展方式是不同的:
let x = {属性名:AssignmentExpression}其中PropertName或者是ComputedPropertyNameLiteralPropertyName至极是IdentifierName不排除保留字.因此let x = {this: this}let x = {class: 10}没有问题.但是,它没有解释为什么会这样,也许它会使语法复杂化或使其模糊不清?


小智 5

this 在Javascript中是一个关键字(不是变量),因此它没有名称.

如果是{ x },x有一个名字,"x",它的值.

但是{ this },this没有名字.this在解释代码时只表示适当的值.