首页 > 解决方案 > 对象属性名称的箭头函数的简写

问题描述

当我有:

const foo = 1;

我可以为对象属性名称设置简写

const bar = {foo}

那是一样的

const bar = {foo: foo} // bar will be {foo: 1}

当我有一个带箭头函数的 const 时,有速记吗?

const foo = () => 1

我必须这样设置,但它不酷

const bar = {foo: foo()}

我想做这样或者更短的东西

const bar = {foo()}  //bar should be {foo: 1} but this will fail

标签: javascriptecmascript-6

解决方案


Looking at the specs, there's no syntax for this.

enter image description here

In your case ObjectLiteral must resolve to { PropertDefinitionList }, which must resolve to PropertyDefinition. Now what could PropertyDefinition be?

It can't be IdentifierReference - that's your first example: {f}.

CoverInitializedName doesn't really fit either. That would look like {f = AssignmentExpression} where AssignmentExpression is defined here.

PropertyName: AssignmentExpression is the conventional syntax: {f: 1}

MethodDefinitionlets you do {f(){ return 1; }};, but that again isn't what you want.

Looks like the verdict is no.


推荐阅读