ECMAScript 2015是一項ECMAScript標準,於2015年6月得到批准。javascript
ES2015是該語言的重要更新,也是自2009年ES5標準化以來該語言的第一次重大更新。如今正在主要JavaScript引擎中實現這些功能。java
有關 ECMAScript 2015語言的完整規範,請參閱ES2015標準。如下簡要介紹僅供參考。jquery
箭頭函數是使用=>語法的函數簡寫。它們在語法上相似於C#,Java 8和CoffeeScript中的相關功能。它們支持表達式和語句體。與函數不一樣,箭頭函數與this周圍的代碼擁有相同的做用域。若是箭頭函數在另外一個函數內,它共享其父函數的「arguments」變量。git
// 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模式簡單。擁有一個方便的聲明形式使類模式更易於使用,並鼓勵互操做性。類支持基於原型的繼承,super調用,實例和靜態方法以及構造函數。es6
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分配提供簡寫,定義方法和進行super調用。它們一塊兒使對象字面量和類聲明更加緊密,讓基於對象的設計更方便。github
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版本中已棄用。大多數引擎如今支持該屬性,但有些則不支持。算法
模板字符串爲構造字符串提供語法糖。這相似於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
被調用者的默認參數值。在函數調用中將數組轉換爲連續的參數。將跟隨參數綁定到數組。Rest 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"; } }
Iterator對象支持自定義迭代,如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 }
生成器使用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); }
支持完整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); }
用於組件定義的模塊的語言級支持。從流行的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));
模塊格式化
Babel能夠將ES2015模塊轉換爲幾種不一樣的格式,包括Common.js,AMD,System和UMD。你甚至能夠建立本身的。
不屬於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
須要額外的polyfill
因爲Babel默認使用common.js模塊,所以它不包含模塊加載器API的polyfill。使用模塊加載器
爲了使用它,您須要告訴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
代理能夠建立具備主機對象可用的所有行爲的對象。可用於攔截,對象虛擬化,日誌記錄/分析等。
// 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 :... }
不支持的功能
因爲ES5的限制,代理不能被轉換或修改。請參閱各類JavaScript引擎中的支持。
Symbols啓用對象狀態的訪問控制。符號容許屬性被鍵入string(如在ES5中)或symbol。Symbols是一種新的原始類型。name調試中使用的可選參數 - 但不是Symbols的一部分。Symbols是獨一無二的(如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
經過polyfill有限的支持
有限的支持須要Babel polyfill。因爲語言限制,某些功能沒法轉換或修改。
在ES2015,內置插件同樣Array,Date和DOM ElementS可被繼承。
// User code of Array subclass class MyArray extends Array { constructor(...args) { super(...args); } } var arr = new MyArray(); arr[1] = 12; arr.length == 2
部分支持
內置的子類可分性應該根據具體狀況進行評估,由於類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) })
來自polyfill的有限支持
Babel polyfill支持大多數這些API 。可是,因爲各類緣由省略了某些功能(例如, String.prototype.normalize須要許多額外的代碼來支持)。
爲binary(b)和octal(o)添加了兩個新的數字文字形式。
0b111110111 === 503 // true 0o767 === 503 // true
僅支持文字形式
babel只能變換0o767而不能變換Number("0o767")。
Promises是異步編程的庫。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)]); })
Reflect API公開對象的運行時元操做。這其實是Proxy 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
保證尾部位置的調用不會無限制地增長堆棧。在無界輸入的狀況下使遞歸算法安全。
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)