上面代码中,变量直接写在大括号里面。这时,属性名就是变量名, 属性值就是变量值。下面是另一个例子。
function f(x, y) {
return {x, y};
}
// 等同于
function f(x, y) {
return {x: x, y: y};
}
f(1, 2) // Object {x: 1, y: 2}
除了属性简写,方法也可以简写。
const o = {
method() {
return "Hello!";
}
};
// 等同于
const o = {
method: function() {
return "Hello!";
}
这种写法用于函数的返回值,将会非常方便。
function getPoint() {
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,
};
简洁写法在打印对象时也很有用。
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';
}
};
上面代码中,f
是一个简写的对象方法,所以obj.f
不能当作构造函数使用。