以下代码失败
let x = {this}
为什么我不能在 this 中使用简写属性名称?
<小时/>来自浏览器的错误消息
chrome 66.0.3359.117 : Uncaught SyntaxError: Unexpected token }
firefox 59.0.1 : this is an invalid identifier
edge 41.16299.371.0 : The use of a keyword for an identifier is invalid
我不太明白这些消息的意思。
<小时/>为了清楚起见,以下代码运行良好
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[Yield] :
- { }
- { PropertyDefinitionList[?Yield] }
- { PropertyDefinitionList[?Yield] , }
- PropertyDefinitionList[Yield] :
- PropertyDefinition[?Yield]
- PropertyDefinitionList[?Yield] , PropertyDefinition[?Yield]
- PropertyDefinition[Yield] :
- IdentifierReference[?Yield]
- CoverInitializedName[?Yield]
- PropertyName[?Yield] : AssignmentExpression[In, ?Yield]
- MethodDefinition[?Yield]
- PropertyName[Yield] :
- LiteralPropertyName
- ComputedPropertyName[?Yield]
- LiteralPropertyName :
- IdentifierName
- StringLiteral
- NumericLiteral
- ComputedPropertyName[Yield] : -[ AssignmentExpression[In, ?Yield] ]
- CoverInitializedName[Yield] :
- IdentifierReference[?Yield] Initializer[In, ?Yield]
- Initializer[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[Yield] :
- Identifier
- [~Yield] yield
- BindingIdentifier[Yield] :
- Identifier
- [~Yield] yield
- LabelIdentifier[Yield] :
- Identifier
- [~Yield] yield
- Identifier :
- IdentifierName but not ReservedWord
这意味着简写 let x = {
标识符 }
不允许保留字作为标识符。和this
是保留字,看11.6.2 Reserved Words以及以后。
另一方面我们看到扩展后的写法是不同的:
let x = {
属性名称 :
赋值表达式 }
其中PropertName是CompulatedPropertyName或LiteralPropertyName,其中IdentifierName不排除保留字。因此let x = {this: this}
或let x = {class: 10}
没问题。
然而,它并没有解释为什么会这样,也许它会使语法复杂化或变得含糊不清?
关于javascript - 带有 *this* 的简写属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49916824/