当使用纯 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 以防你真的想看到它 does work (至少从 Chrome 47 开始)。那么为什么允许这样做,还有其他地方我可以利用缩写吗?
最佳答案
这是在 ES2015 中添加的。在ES2015 Object Initializer syntax ,我们看到对象字面量中的 PropertyDefinition 可以是以下之一:
PropertyDefinition :
- IdentifierReference
- CoverInitializedName
- PropertyName : AssignmentExpression
- MethodDefinition
其中 MethodDefinition 是以下之一:
MethodDefinition :
- PropertyName ( StrictFormalParameters ) { FunctionBody }
- GeneratorMethod
- get PropertyName ( ) { FunctionBody }
- set PropertyName ( PropertySetParameterList ) { FunctionBody }
相比之下,previous ES5 spec's Object Intializer只允许正常的名称/值对和 set
/get
函数:
PropertyAssignment :
- PropertyName : AssignmentExpression
- get PropertyName ( ) { FunctionBody }
- set PropertyName ( PropertySetParameterList ) { FunctionBody }
由于 ES2015 最近才最终确定,因此可能尚未广泛实现。 (在 kangax.github.io 上有一个兼容性表。)
请注意,ES2015 语法还添加了 IdentifierReference 作为有效属性,允许您通过在对象字面量中包含变量的名称来将变量的值包含在对象中:
var foo = "bar";
var obj = {
baz: 3,
foo
};
这个独立的 foo
属性与属性定义 foo: "bar"
的行为相同。
关于javascript - 为什么对象定义不需要函数关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34683753/