function getPoint() {
const x = 1;
const y = 10;
return {x, y};
}
getPoint()
// {x:1, y:10}
这种写法用于函数的返回值,将会非常方便。
CommonJS 模块输出一组变量,就非常合适使用简洁写法
let ms = {};
function getItem (key) {
return key in ms ? ms[key] : null;
}
function setItem (key, value) {
ms[key] = value;
}
function clear () {
ms = {};
}
module.exports = { getItem, setItem, clear };
// 等同于
module.exports = {
getItem: getItem,
setItem: setItem,
clear: clear
};
简洁写法在打印对象时也很有用。
let user = {
name: 'test'
};
let foo = {
bar: 'baz'
};
console.log(user, foo)
// {name: "test"} {bar: "baz"}
console.log({user, foo})
// {user: {name: "test"}, foo: {bar: "baz"}}
上面代码中,console.log直接输出user和foo两个对象时,就是两组键值对,可能会混淆。把它们放在大括号里面输出,就变成了对象的简洁表示法,每组键值对前面会打印对象名,这样就比较清晰了。
注意,简写的对象方法不能用作构造函数,会报错。
const obj = {
f() {
this.foo = 'bar';
}
};
new obj.f() // 报错
上面代码中,f是一个简写的对象方法,所以obj.f不能当作构造函数使用。
参考阮一峰的es6
1249

被折叠的 条评论
为什么被折叠?



