可以同时使用速记属性名称和计算属性名称吗?

Oge*_*gen 1 javascript ecmascript-6

是否可以将简写属性名称(ES2015)与计算属性名称(也是ES2015)结合使用?所以例如......

const a = 'foo';
const o = {
    [a],
}
> o
> {
    "foo": "foo"
  }
Run Code Online (Sandbox Code Playgroud)

Li3*_*357 6

不,这是不可能的.ES2015对象初始值设定项语法不允许将计算属性名称与短序列一起使用.具体而言,a ObjectLiteral由a组成PropertyDefinitionList.A PropertyDefinitionListPropertyDefinitions组成:

12.2.6对象初始化器

句法

ObjectLiteral :
  { }
  { PropertyDefinitionList }
  { PropertyDefinitionList, }

PropertyDefinitionList :
  PropertyDefinition
  PropertyDefinitionList, PropertyDefinition

PropertyDefinition :
  IdentifierReference
  CoverInitializedName
  PropertyName : AssignmentExpression
  MethodDefinition
Run Code Online (Sandbox Code Playgroud)

支持对象文字中计算属性的特定语法PropertyName : AssignmentExpression,因为PropertyName定义为:

PropertyName :
  LiteralPropertyName
  ComputedPropertyName
Run Code Online (Sandbox Code Playgroud)

因此,语法只支持[computedProperty]: value,因为只是PropertyName : AssignmentExpression语法的一部分,而不是PropertyName自身.