ES6語法 學習

ECMAScript 6,也被稱爲ECMAScript 2015是ECMAScript標準的最新版本。6是語言的一個重要更新,並第一次更新語言因爲ES5 2009標準。如今主要JavaScript引擎中實現這些特性正在進行中。看到的ECMAScript 6語言完整規範的ES6標準。
微信小程序支持ES6寫法jquery

ECMAScript 6包括如下新的特色:

Arrows

箭頭是使用=>語法的函數縮寫。它們在語法上相似於C#,Java 8和CoffeeScript中的相關功能。它們既支持語句塊體,又支持返回表達式值的表達式體。與函數不一樣,箭頭與this周圍的代碼共享相同的詞彙。git

// Expression bodies
var odds = evens.map(v => v + 1);
var nums = evens.map((v, i) => v + i);
var pairs = evens.map(v => ({even: v, odd: v + 1}));

// Statement bodies
nums.forEach(v => {
  if (v % 5 === 0)
    fives.push(v);
});

// Lexical this
var bob = {
  _name: "Bob",
  _friends: [],
  printFriends() {
    this._friends.forEach(f =>
      console.log(this._name + " knows " + f));
  }
}

更多信息:[https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions]es6

Class

ES6類是基於原型的OO模式的簡單糖。擁有一個簡單的聲明式表單使得類模式更容易使用,而且鼓勵互操做性。類支持基於原型的繼承,超級調用,實例和靜態方法和構造函數。github

class SkinnedMesh extends THREE.Mesh {
  constructor(geometry, materials) {
    super(geometry, materials);

    this.idMatrix = SkinnedMesh.defaultMatrix();
    this.bones = [];
    this.boneMatrices = [];
    //...
  }
  update(camera) {
    //...
    super.update();
  }
  get boneCount() {
    return this.bones.length;
  }
  set matrixType(matrixType) {
    this.idMatrix = SkinnedMesh[matrixType]();
  }
  static defaultMatrix() {
    return new THREE.Matrix4();
  }
}

更多信息:[https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes]算法

Enhanced Object Literals

對象文字被擴展爲支持在構造中設置原型,foo: foo賦值的簡寫,定義方法,建立超級調用以及使用表達式計算屬性名稱。這些也將對象文字和類聲明緊密地結合在一塊兒,讓基於對象的設計從一些相同的便利中受益。編程

var obj = {
    // __proto__
    __proto__: theProtoObj,
    // Shorthand for ‘handler: handler’
    handler,
    // Methods
    toString() {
     // Super calls
     return "d " + super.toString();
    },
    // Computed (dynamic) property names
    [ 'prop_' + (() => 42)() ]: 42
};

更多信息:[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Object_literals]json

Template Strings

模板字符串爲構造字符串提供了語法糖。這與Perl,Python等中的字符串插值功能相似。可選地,能夠添加標籤以容許定製字符串結構,避免注入攻擊或從字符串內容構建更高級別的數據結構。小程序

// Basic literal string creation
`In JavaScript '\n' is a line-feed.`

// Multiline strings
`In JavaScript this is
 not legal.`

// String interpolation
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`

// Construct an HTTP request prefix is used to interpret the replacements and construction
POST`http://foo.org/bar?a=${a}&b=${b}
     Content-Type: application/json
     X-Credentials: ${credentials}
     { "foo": ${foo},
       "bar": ${bar}}`(myOnReadyStateChangeHandler);

更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings微信小程序

Destructuring 解構

解構容許使用模式匹配進行綁定,支持匹配數組和對象。解構是失敗軟的,相似於標準對象查找foo["bar"],undefined當沒有找到時產生值。設計模式

// list matching
var [a, , b] = [1,2,3];

// object matching
var { op: a, lhs: { op: b }, rhs: c }
       = getASTNode()

// object matching shorthand
// binds `op`, `lhs` and `rhs` in scope
var {op, lhs, rhs} = getASTNode()

// Can be used in parameter position
function g({name: x}) {
  console.log(x);
}
g({name: 5})

// Fail-soft destructuring
var [a] = [];
a === undefined;

// Fail-soft destructuring with defaults
var [a = 1] = [];
a === 1;

更多MDN信息:[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment]

Iterators + For..Of

迭代器對象支持像CLR IEnumerable或Java Iterable這樣的自定義迭代。推廣for..in到自定義基於迭代器的迭代for..of。不要求實現一個數組,使像LINQ這樣的懶惰設計模式成爲可能。

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);
}

迭代是基於這些duck-typed接口(只使用TypeScript類型的語法來講明):

interface IteratorResult {
  done: boolean;
  value: any;
}
interface Iterator {
  next(): IteratorResult;
}
interface Iterable {
  [Symbol.iterator](): Iterator
}

更多信息:[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of]

Generators

生成器使用function*和簡化了迭代器創做yield。一個聲明爲function的函數返回一個Generator實例。生成器是迭代器的子類型,包括附加 next和throw。這些使值可以迴流到生成器,因此yield是一個返回值(或拋出)的表達式。

注意:也能夠用來啓用「await」相似的異步編程,另請參閱ES7 await提議。

var fibonacci = {
  [Symbol.iterator]: function*() {
    var pre = 0, cur = 1;
    for (;;) {
      var temp = pre;
      pre = cur;
      cur += temp;
      yield cur;
    }
  }
}

for (var n of fibonacci) {
  // truncate the sequence at 1000
  if (n > 1000)
    break;
  console.log(n);
}

生成器接口是(僅使用TypeScript語法來進行說明):

interface Generator extends Iterator {
    next(value?: any): IteratorResult;
    throw(exception: any);
}

更多信息:[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols]

Unicode

支持完整Unicode的非中斷添加,包括字符串中的新Unicode字面形式和u處理代碼點的新RegExp 模式,以及在21位代碼點級別處理字符串的新API。這些附加功能支持使用JavaScript構建全球應用程序。

// same as ES5.1
"𠮷".length == 2

// new RegExp behaviour, opt-in ‘u’
"𠮷".match(/./u)[0].length == 2

// new form
"\u{20BB7}"=="𠮷"=="\uD842\uDFB7"

// new String ops
"𠮷".codePointAt(0) == 0x20BB7

// for-of iterates code points
for(var c of "𠮷") {
  console.log(c);
}

更多信息:[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode]

Modules

組件定義模塊的語言級支持。對流行的JavaScript模塊加載器(AMD,CommonJS)的模式進行編碼。運行時行爲由主機定義的默認加載程序定義。隱式異步模型 - 在請求的模塊可用並被處理以前,不執行任何代碼。

// lib/math.js
export function sum(x, y) {
  return x + y;
}
export var pi = 3.141593;
// app.js
import * as math from "lib/math";
alert("2π = " + math.sum(math.pi, math.pi));
// otherApp.js
import {sum, pi} from "lib/math";
alert("2π = " + sum(pi, pi));

一些額外的功能包括export default和export *:

// lib/mathplusplus.js
export * from "lib/math";
export var e = 2.71828182846;
export default function(x) {
    return Math.log(x);
}
// app.js
import ln, {pi, e} from "lib/mathplusplus";
alert("2π = " + ln(e)*pi*2);

更多MDN信息:導入語句[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import],導出語句[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export]

Module Loaders

模塊加載器支持:

動態加載
狀態隔離
全局命名空間隔離
編譯鉤子
嵌套的虛擬化
能夠配置默認的模塊加載器,而且能夠構建新的加載器來評估和加載獨立或受限上下文中的代碼。

// Dynamic loading – ‘System’ is default loader
System.import('lib/math').then(function(m) {
  alert("2π = " + m.sum(m.pi, m.pi));
});

// Create execution sandboxes – new Loaders
var loader = new Loader({
  global: fixup(window) // replace ‘console.log’
});
loader.eval("console.log('hello world!');");

// Directly manipulate module cache
System.get('jquery');
System.set('jquery', Module({$: $})); // WARNING: not yet finalized

Map + Set + WeakMap + WeakSet

用於常見算法的高效數據結構。WeakMaps提供無漏洞的對象鍵表。

/ 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

更多MDN信息:Map[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map],
Set[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set],
WeakMap[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap],
WeakSet[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet]

Proxies

代理使用託管對象可用的所有行爲來建立對象。可用於攔截,對象虛擬化,日誌記錄/分析等

/ Proxying a normal object
var target = {};
var handler = {
  get: function (receiver, name) {
    return `Hello, ${name}!`;
  }
};

var p = new Proxy(target, handler);
p.world === 'Hello, world!';
// Proxying a function object
var target = function () { return 'I am the target'; };
var handler = {
  apply: function (receiver, ...args) {
    return 'I am the proxy';
  }
};

var p = new Proxy(target, handler);
p() === 'I am the proxy';

全部運行時級元操做都有可用的traps:

var handler =
{
  get:...,
  set:...,
  has:...,
  deleteProperty:...,
  apply:...,
  construct:...,
  getOwnPropertyDescriptor:...,
  defineProperty:...,
  getPrototypeOf:...,
  setPrototypeOf:...,
  enumerate:...,
  ownKeys:...,
  preventExtensions:...,
  isExtensible:...
}

更多信息:MDN代理 [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy]

Symbols

符號啓用對象狀態的訪問控制。符號容許屬性被鍵入string(如在ES5中)或symbol。符號是一種新的原始類型。description用於調試的可選參數 - 但不是身份的一部分。符號是獨一無二的(像gensym),但不是私人的,由於他們經過像反射功能暴露Object.getOwnPropertySymbols。

var MyClass = (function() {

  // module scoped symbol
  var key = Symbol("key");

  function MyClass(privateData) {
    this[key] = privateData;
  }

  MyClass.prototype = {
    doStuff: function() {
      ... this[key] ...
    }
  };

  return MyClass;
})();

var c = new MyClass("hello")
c["key"] === undefined

更多信息:MDN符號 [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol]

Subclassable Built-ins

在ES6,內置插件同樣Array,Date和DOM ElementS可被繼承。

Ctor目前命名的函數的對象構造使用兩個階段(都是虛擬調度的):

調用Ctor[@@create]來分配對象,安裝任何特殊的行爲
在新實例上調用構造函數進行初始化
已知的@@create符號能夠經過Symbol.create。內置插件如今@@create顯式公開它們。

// Pseudo-code of Array
class Array {
    constructor(...args) { /* ... */ }
    static [Symbol.create]() {
        // Install special [[DefineOwnProperty]]
        // to magically update 'length'
    }
}

// User code of Array subclass
class MyArray extends Array {
    constructor(...args) { super(...args); }
}

// Two-phase 'new':
// 1) Call @@create to allocate object
// 2) Invoke constructor on new instance
var arr = new MyArray();
arr[1] = 12;
arr.length == 2

Math + Number + String + Array + 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].find(x => x == 3) // 3
[1, 2, 3].findIndex(x => x == 2) // 1
[1, 2, 3, 4, 5].copyWithin(3, 0) // [1, 2, 3, 1, 2]
["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) })

更多MDN信息:Number[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number],
Math[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math],
Array.from[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from],
Array.of[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of],
Array.prototype.copyWithin[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin],
Object.assign[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign]

Binary and Octal Literals

爲二進制(b)和八進制(o)添加了兩個新的數字文字形式。

0b111110111 === 503 // true
0o767 === 503 // true

承諾

Promise是一個用於異步編程的庫。承諾是對將來價值的一流表示。Promises被用在許多現有的JavaScript庫中。

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)]);
})

更多信息:MDN諾言[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise]

Reflect API

全反射API將對象的運行時級元操做公開。這其實是代理API的反面,而且容許進行與代理陷阱相同的元操做。對於實現代理尤爲有用。

//no code
更多信息:MDN反映 [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect]

Tail Calls

調用尾部位置保證不會無限增加堆棧。在無界輸入的狀況下使遞歸算法安全。

function factorial(n, acc = 1) {
    'use strict';
    if (n <= 1) return acc;
    return factorial(n - 1, n * acc);
}

// Stack overflow in most implementations today,
// but safe on arbitrary inputs in ES6
factorial(100000)

https://github.com/lukehoban/es6features#readme[https://github.com/lukehoban/es6features#readme]

相關文章
相關標籤/搜索