ECMAScript 2015功能的詳細概述。基於盧克·霍本的e6features回購。html
ECMAScript 2015是2015年6月批准的ECMAScript標準。jquery
ES2015是語言的重要更新,自2009年ES5標準化以來語言的第一次重大更新。主要JavaScript引擎中的這些功能的實現正在進行中。git
有關ECMAScript 2015語言的完整規範,請參閱ES2015標準。es6
箭頭是使用=>
語法的縮寫。它們在語法上相似於C#,Java 8和CoffeeScript中的相關功能。他們支持表達和聲明機構。與函數不一樣,箭頭this
與其周圍的代碼共享相同的詞法。若是一個箭頭在另外一個函數內,它將共享其父函數的「arguments」變量。github
// Expression bodies var odds = evens.map(v => v + 1); var nums = evens.map((v, i) => v + i); // 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)); } }; // Lexical arguments function square() { let example = () => { let numbers = []; for (let number of arguments) { numbers.push(number * number); } return numbers; }; return example(); } square(2, 4, 7.5, 8, 11.5, 21); // returns: [4, 16, 56.25, 64, 132.25, 441]
ES2015課程是基於原型的OO模式的簡單糖。擁有單一的方便的聲明式表單使得類模式更易於使用,並鼓勵互操做性。類支持基於原型的繼承,超級調用,實例和靜態方法和構造函數。web
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(); } }
擴展了對象文字,以支持在構建中設計原型,foo: foo
分配簡寫,定義方法和進行超級調用。總而言之,這些也使對象文字和類聲明更加緊密,讓基於對象的設計也受益於一些相同的便利。算法
var obj = { // Sets the prototype. "__proto__" or '__proto__' would also work. __proto__: theProtoObj, // Computed property name does not set prototype or trigger early error for // duplicate __proto__ properties. ['__proto__']: somethingElse, // Shorthand for ‘handler: handler’ handler, // Methods toString() { // Super calls return "d " + super.toString(); }, // Computed (dynamic) property names [ "prop_" + (() => 42)() ]: 42 };
該
__proto__
屬性須要本機支持,而且在之前的ECMAScript版本中已被棄用。大多數引擎如今支持該屬性,但有些則不支持。另外請注意,只有Web瀏覽器才能實現它,如附件B所示。它在Node中可用。typescript
模板字符串提供構造字符串的語法糖。這與Perl,Python等中的字符串插入功能相似。可選地,能夠添加標籤以容許定製字符串構造,避免注入攻擊或從字符串內容構建更高級別的數據結構。編程
// Basic literal string creation `This is a pretty little template string.` // Multiline strings `In ES5 this is not legal.` // Interpolate variable bindings var name = "Bob", time = "today"; `Hello ${name}, how are you ${time}?` // Unescaped template strings String.raw`In ES5 "\n" is a line-feed.` // Construct an HTTP request prefix is used to interpret the replacements and construction GET`http://foo.org/bar?a=${a}&b=${b} Content-Type: application/json X-Credentials: ${credentials} { "foo": ${foo}, "bar": ${bar}}`(myOnReadyStateChangeHandler);
解構容許使用模式匹配進行綁定,並支持匹配的數組和對象。破壞是失敗軟件,相似於標準對象查找foo["bar"]
,undefined
當找不到時生成值。json
// list matching var [a, ,b] = [1,2,3]; a === 1; b === 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; // Destructuring + defaults arguments function r({x, y, w = 10, h = 10}) { return x + y + w + h; } r({x:1, y:2}) === 23
Callee評估的默認參數值。將數組轉換爲函數調用中的連續參數。將後跟參數綁定到數組。休息arguments
更直接地替代了對常見病例的需求。
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 function f(x, y, z) { return x + y + z; } // Pass each elem of array as argument f(...[1,2,3]) == 6
塊結合結構。let
是新的var
。const
是單獨分配。靜態限制在分配前禁止使用。
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"; } }
迭代器對象啓用自定義迭代,如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); }
迭代基於這些鴨型接口(僅使用TypeScript類型語法):
interface IteratorResult { done: boolean; value: any; } interface Iterator { next(): IteratorResult; } interface Iterable { [Symbol.iterator](): Iterator }
2.8.1. 經過polyfill支持
爲了使用迭代器,您必須包括Babel polyfill。
發電機使用function*
和簡化迭代器創做yield
。聲明爲function *的函數返回一個Generator實例。發生器是迭代器的子類型,其包括附加next
和throw
。這些使值返回到生成器中,因此yield
返回值(或throws)的表達式形式也是如此。
注意:也能夠用來啓用「等待」的異步編程,另請參閱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); }
2.9.1. 經過polyfill支持
爲了使用發電機,您必須包括Babel polyfill。
在Babel 6.0中刪除
支持完整Unicode u
的不間斷補充,包括字符串中的新unicode文字形式和處理代碼點的新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); }
組件定義模塊的語言級支持。編輯流行的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"; console.log("2π = " + math.sum(math.pi, math.pi)); // otherApp.js import {sum, pi} from "lib/math"; console.log("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.exp(x); } // app.js import exp, {pi, e} from "lib/mathplusplus"; console.log("e^π = " + exp(pi));
2.12.1. 模塊格式化器
Babel能夠將ES2015模塊轉換成幾種不一樣的格式,包括Common.js,AMD,System和UMD。你甚至能夠建立本身的。有關詳細信息,請參閱模塊文檔。
2.13.1. 不是ES2015的一部分
這在ECMAScript 2015規範中被保留爲實現定義。最終標準將在WHATWG的Loader規範中,但目前正在進行中。如下是之前的ES2015草案。
模塊裝載機支持:
能夠配置默認模塊加載程序,而且能夠構造新的裝載器,以在隔離或約束上下文中評估和加載代碼。
// 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
2.13.2. 須要額外的聚合物填充
因爲Babel默認使用common.js模塊,它不包括模塊加載程序API的polyfill。獲得它在這裏。
2.13.3. 使用模塊裝載機
爲了使用這個,你須要告訴Babel使用
system
模塊格式化程序。另請務必查看System.js
經常使用算法的高效數據結構。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
2.14.1. 經過polyfill支持
爲了在全部環境中支持「地圖」,「集合」,「WeakMaps」和「WeakSets」,您必須包括Babel polyfill。
代理能夠建立具備可用於託管對象的所有行爲的對象。可用於攔截,對象虛擬化,日誌/分析等。
// 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";
全部運行級元操做都有陷阱:
var handler = { // target.prop get: ..., // target.prop = value set: ..., // 'prop' in target has: ..., // delete target.prop deleteProperty: ..., // target(...args) apply: ..., // new target(...args) construct: ..., // Object.getOwnPropertyDescriptor(target, 'prop') getOwnPropertyDescriptor: ..., // Object.defineProperty(target, 'prop', descriptor) defineProperty: ..., // Object.getPrototypeOf(target), Reflect.getPrototypeOf(target), // target.__proto__, object.isPrototypeOf(target), object instanceof target getPrototypeOf: ..., // Object.setPrototypeOf(target), Reflect.setPrototypeOf(target) setPrototypeOf: ..., // for (let i in target) {} enumerate: ..., // Object.keys(target) ownKeys: ..., // Object.preventExtensions(target) preventExtensions: ..., // Object.isExtensible(target) isExtensible :... }
2.15.1. 不支持的功能
因爲ES5的限制,代理不能被淹沒或多重填充。請參閱各類JavaScript引擎的支持。
符號容許對象狀態的訪問控制。符號容許屬性由string
(如ES5)或symbol
。符號是一種新的原始類型。name
在調試中使用的可選參數 - 但不是身份的一部分。符號是獨特的(如gensym),但不是私有的,由於它們經過反射功能暴露出來Object.getOwnPropertySymbols
。
(function() { // module scoped symbol var key = Symbol("key"); function MyClass(privateData) { this[key] = privateData; } MyClass.prototype = { doStuff: function() { ... this[key] ... } }; // Limited support from Babel, full support requires native implementation. typeof key === "symbol" })(); var c = new MyClass("hello") c["key"] === undefined
2.16.1. 有限的支持經過polyfill
有限的支持須要Babel polyfill。因爲語言限制,某些功能不能被淹沒或多重填充。有關詳細信息,請參閱core.js的注意事項部分。
在ES2015中,內置的Array
,Date
和DOM Element
能夠被子類化。
// User code of Array subclass class MyArray extends Array { constructor(...args) { super(...args); } } var arr = new MyArray(); arr[1] = 12; arr.length == 2
2.17.1. 部分支持
內置的子類能夠根據具體狀況進行評估,由於類
HTMLElement
能夠被子類化,而許多例如Date
,Array
而且Error
不能因爲ES5引擎限制。
許多新的庫增長,包括核心數學庫,數組轉換助手和用於複製的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) })
2.18.1. 有限的支持從polyfill
這些API大部分都是由Babel polyfill支持的。然而,因爲各類緣由(例如
String.prototype.normalize
須要大量附加代碼來支持),某些功能被省略。您能夠在這裏找到更多的聚合物。
爲binary(b
)和octal(o
)添加了兩個新的數字文字形式。
0b111110111 === 503 // true 0o767 === 503 // true
2.19.1. 只支持文字形式
巴別隻能轉變
0o767
而不是Number("0o767")
。
承諾是用於異步編程的庫。承諾是未來可能提供的價值的第一類表明。許多現有的JavaScript庫都使用Promises。
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)]); })
2.20.1. 經過polyfill支持
爲了支持Promises,您必須包括Babel polyfill。
全反射API暴露了對象的運行時級元操做。這其實是代理API的逆向,並容許調用對應於與代理陷阱相同的元操做的調用。特別適用於執行代理。
var O = {a: 1}; Object.defineProperty(O, 'b', {value: 2}); O[Symbol('c')] = 3; Reflect.ownKeys(O); // ['a', 'b', Symbol(c)] function C(a, b){ this.c = a + b; } var instance = Reflect.construct(C, [20, 22]); instance.c; // 42
2.21.1. 經過polyfill支持
爲了使用Reflect API,您必須包括Babel polyfill。
尾部的呼叫保證不會無限制地增加堆棧。使遞歸算法面對無界輸入時的安全。
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 ES2015 factorial(100000)