ECMAScript 6 簡介


ECMAScript 6 是JavaScript的下一個標准,正處在快速開發之中,大部分已經完成了,預計將在2014年正式發布。Mozilla將在這個標准的基礎上,推出JavaScript 2.0。

ECMAScript 6 的目標,是使得JavaScript可以用來編寫復雜的應用程序、函數庫和代碼的自動生成器(code generator)。

最新的瀏覽器已經部分支持ECMAScript 6 的語法,可以通過《ECMAScript 6 瀏覽器兼容表》查看瀏覽器支持情況。

ECMAScript 6 新內容一覽

  1. let, const (定義塊級局部變量), 函數在塊級域中

  2. 解構: let {x, y} = pt; let [s, v, o] = triple(); (如可以 let pt = {x:2, y:-5}).

  3. 參數設置默認設置: function f(x, y=1, z=0) {...}

  4. rest: function g(i, j, ...r) { return r.slice(i, j); } (而不是瘋狂地使用arguments).

  5. spread: let a = [0,1,2,3], o = new Something(...a);

  6. proxies: let obj = Proxy.create(handler, proto). 簡單地說,就是類對象元素的符號重載.

  7. weak map: let map = new WeakMap. 當你有循環應用的時候用它.

  8. generators: function* gen() { yield 1; yield 2; } 事實上, gen() 返回一個有next()屬性的對象

  9. 迭代器: for (var [key, val] of items(x)) { alert(key + ',' + val); }. Iterators 可以是 generators 或者 proxies.

  10. array and generator comprehension: [a+b for (a in A) for (b in B)] (array comprehension), (x for (x of generateValues()) if (x.color === 'blue')) (generator expression).

  11. 二進制數據: const Pixel = new StructType({x:uint32, y:uint32, color:Color}) (此處Color本身就是一個結構類型), new ArrayType(Pixel, 3).

  12. 類語法, 包含 extends, prototype, and super:

    class Point extends Base {
      constructor(x,y) {
        super();
        this[px] = x, this[py] = y;
        this.r = function() { return Math.sqrt(x*x + y*y); }
      }
      get x() { return this[px]; }
      get y() { return this[py]; }
      proto_r() { return Math.sqrt(this[px] * this[px] +
          this[py] * this[py]); }
      equals(p) { return this[px] === p[px] &&
          this[py] === p[py]; }
    }
  13.  模塊:
    module math {
      export function sum(x, y) {
        return x + y;
      }
      export var pi = 3.141593;
    }
    import {sum, pi} from math;
    alert(sum(pi,pi));

     

  14. quasis: multiline, 可擴展的預處理字符串. You are ${age} years old.
    // The following regexp spans multiple lines.
    re`line1: (words )*
    line2: \w+`
    
    // It desugars to:
    re({raw:'line1: (words )*\nline2: \w+',
        cooked:'line1: (words )*\nline2: \w+'}) 

參考資料

后續文章將陸續詳細介紹上述新特性。

本文同步自我的github博客。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM