以下代码失败
let x = {this}
为什么我不能用这个简写属性名?
来自浏览器的错误消息
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})
According to the ECMA spec(我把粗体放入了重要的东西):
12.2.6 Object Initializer
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.
Syntax
- 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 Identifiers
Syntax
- IdentifierReference [收益率]: 识别码 [〜收益率]收益率
- BindingIdentifier [收益率]: 识别码 [〜收益率]收益率
- LabelIdentifier [收益率]: 识别码 [〜收益率]收益率
- 标识符: IdentifierName但不是ReservedWord
这意味着在简写中let x = {
Identifier}
不允许保留字作为标识符。 this
是一个保守的词,看看11.6.2 Reserved Words和向前。另一方面,我们看到扩展的写作方式是不同的:
let x = {
PropertyName:
AssignmentExpression}
其中PropertName是ComputedPropertyName或LiteralPropertyName,它是不排除保留字的IdentifierName。因此let x = {this: this}
或let x = {class: 10}
没有问题。但是,它没有解释为什么会这样,也许它会使语法复杂化或使其模糊不清?
Javascript中的this
是一个关键字(不是变量),因此它没有名称。
在{ x }
的情况下,x有一个名字,“x”,它的值。
但{ this }
,this
没有名字。 this
只是在解释代码时表示正确的值。