ES6专题

Symbol

魔术字符串指的是,在代码之中多次出现、与代码形成强耦合的某一个具体的字符串或者数值。 风格良好的代码,应该尽量消除魔术字符串,改由含义清晰的常量代替。

const shapeType = {
  triangle: 'Triangle'
};

function getArea(shape, options) {
  let area = 0;
  switch (shape) {
    case shapeType.triangle:
      area = .5 * options.width * options.height;
      break;
  }
  return area;
}

getArea(shapeType.triangle, { width: 100, height: 100 });
复制代码

上面代码中,我们把Triangle写成shapeType对象的triangle属性,这样就消除了强耦合。 如果仔细分析,可以发现shapeType.triangle等于哪个值并不重要,只要确保不会跟其他shapeType属性的值冲突即可。因此,这里就很适合改用 Symbol 值。 不用为常量去费力想初始值了

const shapeType = {
  triangle: Symbol()
};
复制代码

async函数

  1. await的作用就是为了解决回调嵌套地狱
const user = new User();
user.name = "Leo";
await connection.manager.save(user);

const photo1 = new Photo();
photo1.url = "me.jpg";
photo1.user = user;
await connection.manager.save(photo1);
复制代码

由于photo实例的user属性需要用到上一段中创建的user,所以对connection.manager.save(user);这个方法使用了await标志,使用这个标志,表示其后的语句需要等待await方法执行完毕后再执行

转载于:https://juejin.im/post/5cf0c75bf265da1bba58ea93

猜你喜欢

转载自blog.csdn.net/weixin_34050005/article/details/91453042
ES6