ES 6 中對象屬性的簡潔表示法

ES6 允許在對象中直接寫入變量和函數,作爲對象的屬性和方法。此種方式簡化了對象的定義。

一.屬性的簡潔表示法

1.基本定義

  • 屬性和方法的簡潔表示

    //一 屬性的簡潔表示
    const foo = 'bar';
    const baz = {foo};
    baz // {foo: "bar"}
    // 等同於
    const baz = {foo: foo};
    
    //二 方法的簡潔表示
    const o = {
      method() {
    	return "Hello!";
      }
    };
    // 等同於
    const o = {
      method: function() {
    	return "Hello!";
      }
    };
    

2.對象屬性和方法簡寫使用範例

  • ① 對象屬性簡寫使用範例

    function f(x, y) {
      return {x, y};
    }
    
    // 等同於
    
    function f(x, y) {
      return {x: x, y: y};
    }
    
    f(1, 2) // Object {x: 1, y: 2}
    
  • ② 對象屬性和方法簡寫使用範例

    let birth = '2000/01/01';
    
    const Person = {
    
      name: '張三',
    
      //等同於birth: birth
      birth,
    
      // 等同於hello: function ()...
      hello() { console.log('我的名字是', this.name); }
    
    };
    
  • ③ 屬性簡寫,方便定義函數返回值

    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(key),
      setItem: setItem(key,value),
      clear: clear()
    };
    
  • ⑤ 屬性的賦值器(setter)和取值器(getter),也使用簡寫的方式

    const cart = {
      _wheels: 4,
    
      get wheels () {
    	return this._wheels;
      },
    
      set wheels (value) {
    	if (value < this._wheels) {
    	  throw new Error('數值太小了!');
    	}
    	this._wheels = value;
      }
    }
    
  • ⑥ 使用簡寫的方式打印對象

    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"}}
    
發佈了181 篇原創文章 · 獲贊 65 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章