es6新增加:对象字面量简写(Object Literal Shorthand)、对象方法简写(Object Method Shorthand)、计算对象键(Object key)
es5对象字面量:
var type = 'rock'; var heat = '50%'; var music = { type: type, heat: heat }; console.log(music); // Object {type: "rock", heat: "50%"}
es6对象字面量:
var type = 'rock'; var heat = '50%'; var music = { type, heat }; console.log(music); // Object {type: "rock", heat: "50%"}
ES5返回一个对象
function getMusic() { var type = 'rock'; var heat = '50%'; return { type: type, heat: heat }; } console.log(getMusic().type); // rock console.log(getMusic().heat); // 50%
ES6返回一个对象
function getMusic() { var type = 'rock'; var heat = '50%'; return { type, heat }; } console.log(getMusic().type); // rock console.log(getMusic().heat); // 50%
在 ECMAScript 2015 之前,JavaScript 里的对象字面量(也叫对象初始化器)功能很弱。它只能定义两种属性:
ES2015 改进对象字面量:
- 在对象构造的过程中设置原型
- 速记方法定义
- 调用父类方法
- 计算属性名称
速记方法定义(shorthand method definition):
es5写法:
var obj = {
name: 'jeff', getName: function () {
return this.name;
}
}
es6写法:
var obj = { name: 'jeff', getName () { return this.name; } }