在 ES2015 中,对象字面值扩展支持在创建时设置原型,简写了 foo: foo
形式的属性赋值,方法定义,支持父方法调用,以及使用表达式动态计算属性名。总之,这些也使对象字面值和类声明更加紧密地联系起来,让基于对象的设计从这些便利中更加受益。
var obj = {
// __proto__
__proto__: theProtoObj,
// Shorthand for ‘handler: handler’
handler,
// Methods
toString() {
// Super calls
return "d " + super.toString();
},
// Computed (dynamic) property names
[ ‘prop_‘ + (() => 42)() ]: 42
};
var a = "foo",
b = 42,
c = {};
var o = {
a: a,
b: b,
c: c
};
在 ECMAScript 2015 中,有更简短的标记可以实现同样的效果:
var a = ‘foo‘,
b = 42,
c = {};
// Shorthand property names (ES2015)
var o = {a, b, c};
// In other words,
console.log((o.a === {a}.a)); // true
对象属性也可以是一个函数、getter、setter方法。
let o = {
property: function (parameters) {},
get property() {},
set property(value) {}
}
ECMAScript 2015 引入了一种简短写法, function
关键字也可以丢掉。
// Shorthand method names (ES6)
let o = {
property(parameters) {},
get property() {},
set property(value) {}
}
对象字面量表示法和 JavaScript Object Notation(JSON)是不同的。虽然他们看起来相似,不同点有:
"property": value
syntax 形式的属性定义。属性名必须用双引号括起来。且属性定义不允许使用简便写法。true
,false
,null
或其他(JSON)对象。Date
等对象,经 JSON.parse()
处理后,会变成字符串。JSON.parse()
不会处理计算的属性名,会当做错误抛出。ES6 增强的对象字面量 (Enhanced Object literals)
原文:https://www.cnblogs.com/clipboard/p/13876019.html