为什么在对象定义中不需要 function 关键字?

3

在使用纯JavaScript时,我注意到有些人会将他们的对象定义为:

var oddObject = {
    someProperty: 'random1',

  // NOTE: No function keyword. Why does this work and are there
  //       other places this is also not required?
  someFunction() { return "boring value"; },
  someOtherProperty: 'random2'
}

var el = document.getElementById("result");
el.innerHTML = oddObject.someFunction();

我制作了一个fiddle,以防您真的想看到它可以工作(至少在Chrome 47中是这样)。那么为什么允许这样做?还有其他可以利用缩写的地方吗?


1
这是一种语法糖,例如:http://ariya.ofilabs.com/2013/03/es6-and-method-definitions.html - Dave Newton
从ECMAScript 2015(ES6)开始,引入了对象初始化器上方法定义的更短语法。 - hindmost
所以在我使用Babel或其他转换器之前,这还不被推荐使用吗? - drew_w
1
取决于你需要针对什么,我猜。 - Dave Newton
你可以在这里看到支持新功能的平台:https://kangax.github.io/compat-table/es6/#test-object_literal_extensions_shorthand_methods。 - Mike Cluck
1个回答

2
这是在ES2015中添加的。在ES2015对象初始化器语法中,我们可以看到对象字面量中的PropertyDefinition可以是以下之一:

PropertyDefinition

  • IdentifierReference
  • CoverInitializedName
  • PropertyNameAssignmentExpression
  • MethodDefinition

其中MethodDefinition之一是:

MethodDefinition

  • PropertyNameStrictFormalParameters){FunctionBody}
  • GeneratorMethod
  • get PropertyName(){FunctionBody}
  • set PropertyNamePropertySetParameterList){FunctionBody}
相比之下,以前的ES5规范中的对象初始化器仅允许普通的名称/值对和set/get函数:

PropertyAssignment :

  • PropertyNameAssignmentExpression
  • get PropertyName(){FunctionBody}
  • set PropertyNamePropertySetParameterList){FunctionBody}
由于ES2015最近才完成,因此可能尚未广泛实施。 (在kangax.github.io上有一个兼容性表。)
请注意,ES2015语法还将IdentifierReference添加为有效属性,允许您通过在对象文字中包含其名称来包含变量的值:
var foo = "bar";
var obj = {
    baz: 3,
    foo
};

这个独立的 foo 属性与属性定义 foo: "bar" 的作用相同。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接