上面代码中,变量直接写在大括号里面。这时,属性名就是变量名, 属性值就是变量值。下面是另一个例子。

    1. function f(x, y) {
    2. return {x, y};
    3. }
    4. // 等同于
    5. function f(x, y) {
    6. return {x: x, y: y};
    7. }
    8. f(1, 2) // Object {x: 1, y: 2}

    除了属性简写,方法也可以简写。

    1. const o = {
    2. method() {
    3. return "Hello!";
    4. }
    5. };
    6. // 等同于
    7. const o = {
    8. method: function() {
    9. return "Hello!";
    10. }

    这种写法用于函数的返回值,将会非常方便。

    1. function getPoint() {
    2. const y = 10;
    3. return {x, y};
    4. }
    5. getPoint()
    6. // {x:1, y:10}

    CommonJS 模块输出一组变量,就非常合适使用简洁写法。

    1. let ms = {};
    2. function getItem (key) {
    3. return key in ms ? ms[key] : null;
    4. }
    5. function setItem (key, value) {
    6. ms[key] = value;
    7. }
    8. function clear () {
    9. ms = {};
    10. }
    11. module.exports = { getItem, setItem, clear };
    12. module.exports = {
    13. getItem: getItem,
    14. setItem: setItem,
    15. };

    简洁写法在打印对象时也很有用。

    1. let user = {
    2. name: 'test'
    3. };
    4. let foo = {
    5. bar: 'baz'
    6. };
    7. console.log(user, foo)
    8. // {name: "test"} {bar: "baz"}
    9. console.log({user, foo})
    10. // {user: {name: "test"}, foo: {bar: "baz"}}

    上面代码中,console.log直接输出userfoo两个对象时,就是两组键值对,可能会混淆。把它们放在大括号里面输出,就变成了对象的简洁表示法,每组键值对前面会打印对象名,这样就比较清晰了。

    1. const obj = {
    2. f() {
    3. this.foo = 'bar';
    4. }
    5. };

    上面代码中,f是一个简写的对象方法,所以obj.f不能当作构造函数使用。