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"}}
    
发布了170 篇原创文章 · 获赞 61 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/NDKHBWH/article/details/103879327