ES6 允许直接写入变量和函数,作为对象的属性和方法,这样的书写更加简洁。

属性简写

  1. var foo = 'bar';
  2. var baz1 = { foo };
  3. console.log(baz);
  4. // 等同于
  5. var baz2 = { foo: foo };
  6. console.log(baz);

返回值简写

  1. // demo2
  2. function f(x, y) {
  3. return { x, y };
  4. }
  5. // 旧的写法
  6. function f1(x, y) {
  7. return { x: x, y: y };
  8. }
  9. f(1, 2);

方法简写

  1. var o1 = {
  2. method() {
  3. return 'hello';
  4. },
  5. };
  6. // 等同于
  7. var o2 = {
  8. method: function() {
  9. return 'hello';
  10. },
  11. };
  12. // 实例
  13. var birth = '2016/11/7';
  14. var person = {
  15. name: 'tom',
  16. birth,
  17. hello() {
  18. console.log('name is', this.name);
  19. },
  20. };

调整CommonJS模块输出变量写法

  1. // 可以据此修改项目的common.js,以及require的return方法
  2. var ms = {};
  3. function getItem(key){
  4. return key in ms? ms[key]:null;
  5. }
  6. function setItem(key,value){
  7. ms[key] = value;
  8. }
  9. function clear(){
  10. ms = {};
  11. }
  12. model.exports = {getItem,setItem,clear};
  13. // 等同于
  14. model.exports = {
  15. getItem:getItem,
  16. setItem:setItem,
  17. clear:clear
  18. };