ES6 - 对象扩展(增强字面量)

/**
 * 对象的扩展
 * 
 * 增强对象字面量
 * 
 * 解决问题:缩减代码
 */

{
  /**
   * 1.属性简表示法
   * 变量foo直接写在大括号里面。这时,属性名就是变量名, 属性值就是变量值
   */
  const foo = 'bar';
  const baz = { foo };
  // baz // {foo: "bar"}

  // 等同于
  // const baz = { foo: foo };


  /**
   * 方法简写
   */
  const o1 = {
    method() {
      return "Hello!";
    }
  };

  // 等同于

  const o2 = {
    method: function () {
      return "Hello!";
    }
  };
}

{
  // 例子1
  let birth = '2000/01/01';

  const Person = {

    name: '张三',

    //等同于birth: birth
    birth,

    // 等同于hello: function ()...
    hello() { console.log('我的名字是', this.name); }
  };



  // 例子2
  function createBookShop(inventory) {
    return {
      inventory,    //属性简写  inventory:inventory,
      // inventoryValue: function () {
      inventoryValue() {
        return this.inventory.reduce((total, book) => total +
          book.price, 0);
      },
      //priceForTitle: function (title) {
      priceForTitle(title) {
        return this.inventory.find(book => book.title === title)
          .price;
      }
    }
  }

  const inventory = [
    { title: "Vue", price: 10 },
    { title: "Angular", price: 15 }
  ];

  const bookShop = createBookShop(inventory);
  console.log(bookShop.inventoryValue());         //25
  console.log(bookShop.priceForTitle("Angular")); //15

}


posted @ 2019-12-07 23:57  【唐】三三  阅读(192)  评论(0编辑  收藏  举报