ES6新特性你学全了吗

学习地址:https://babeljs.io/docs/en/learn

es6以及开始在业务中大量使用,会简化我们很多的繁杂代码、增加可读性,但是新增特性很多,一直没有做梳理、一般也是用到哪儿学到哪儿,以下梳理了大多数新特性,都是业务上可以接触并且实践的

大纲整理:

  • 箭头语法糖

    var nums = evens.map((v, i) => v + i);
    
  • 新增类,基于原型函数的继承

    class SkinnedMesh extends THREE.Mesh {
      constructor(geometry, materials) {
        super(geometry, materials);
    
        this.idMatrix = SkinnedMesh.defaultMatrix();
        this.bones = [];
        this.boneMatrices = [];
        //...
      }
      update(camera) {
        //...
        super.update();
      }
      static defaultMatrix() {
        return new THREE.Matrix4();
      }
    }
    
  • Default + Rest + Spread,解决函数调用的常见问题

    function f(x, y=12) {
      // y is 12 if not passed (or passed as undefined)
      return x + y;
    }
    // f(3) == 15
    
    function f(x, ...y) {
      // y is an Array
      return x * y.length;
    }
    f(3, "hello", true) == 6
    
  • 加入let块作用域、cosnt静态声明

    function f() {
      {
        let x;
        {
          // this is ok since it's a block scoped name
          const x = "sneaky";
          // error, was just defined with `const` above
          x = "foo";
        }
        // this is ok since it was declared with `let`
        x = "bar";
        // error, already declared above in this block
        let x = "inner";
      }
    }
    
  • iterator 和 for....of, 业务中用的不多还是多了解下

    let fibonacci = {
      [Symbol.iterator]() {
        let pre = 0, cur = 1;
        return {
          next() {
            [pre, cur] = [cur, pre + cur];
            return { done: false, value: cur }
          }
        }
      }
    }
    
    for (var n of fibonacci) {
      // truncate the sequence at 1000
      if (n > 1000)
        break;
      console.log(n);
    }
    
  • modules,基于AMD,CommonJS模块化的模式,在可用和处理所请求的模块之前,不会执行任何代码

    // lib/math.js
    export function sum(x, y) {
      return x + y;
    }
    export var pi = 3.141593;
    
    import * as math from "lib/math";
    console.log("2π = " + math.sum(math.pi, math.pi));
    
    import {sum, pi} from "lib/math";
    console.log("2π = " + sum(pi, pi));
    
  • Map 、Set(WeakMap、WeakSet)

    // Sets
    var s = new Set();
    s.add("hello").add("goodbye").add("hello");
    s.size === 2;
    s.has("hello") === true;
    
    // Maps
    var m = new Map();
    m.set("hello", 42);
    m.set(s, 34);
    m.get(s) == 34;
    
    // Weak Maps
    var wm = new WeakMap();
    wm.set(s, { extra: 42 });
    wm.size === undefined
    
    // Weak Sets
    var ws = new WeakSet();
    ws.add({ data: 42 });
    // Because the added object has no other references, it will not be held in the set
    
  • Math + Number + String + Object APIs,增加了很多方法、以及可以用于复制的Object.assign,业务中很多用处,有宝藏

Number.EPSILON
Number.isInteger(Infinity) // false
Number.isNaN("NaN") // false

Math.acosh(3) // 1.762747174039086
Math.hypot(3, 4) // 5
Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2) // 2

"abcde".includes("cd") // true
"abc".repeat(3) // "abcabcabc"

Array.from(document.querySelectorAll("*")) // Returns a real Array
Array.of(1, 2, 3) // Similar to new Array(...), but without special one-arg behavior
[0, 0, 0].fill(7, 1) // [0,7,7]
[1,2,3].findIndex(x => x == 2) // 1
["a", "b", "c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"]
["a", "b", "c"].keys() // iterator 0, 1, 2
["a", "b", "c"].values() // iterator "a", "b", "c"

Object.assign(Point, { origin: new Point(0,0) })
  • promise, I love promise ,解决回调地狱的新异步方案,很多库flyio、axios都使用了promise

    function timeout(duration = 0) {
        return new Promise((resolve, reject) => {
            setTimeout(resolve, duration);
        })
    }
    
    var p = timeout(1000).then(() => {
        return timeout(2000);
    }).then(() => {
        throw new Error("hmm");
    }).catch(err => {
        return Promise.all([timeout(100), timeout(200)]);
    })