ECMAScript 6,也被称为ECMAScript 2015是ECMAScript标准的最新版本。6是语言的一个重要更新,并第一次更新语言因为ES5 2009标准。如今主要JavaScript引擎中实现这些特性正在进行中。看到的ECMAScript 6语言完整规范的ES6标准。
微信小程序支持ES6写法jquery
箭头是使用=>语法的函数缩写。它们在语法上相似于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
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]算法
对象文字被扩展为支持在构造中设置原型,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
模板字符串为构造字符串提供了语法糖。这与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微信小程序
解构容许使用模式匹配进行绑定,支持匹配数组和对象。解构是失败软的,相似于标准对象查找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]
迭代器对象支持像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]
生成器使用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字面形式和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]
组件定义模块的语言级支持。对流行的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]
模块加载器支持:
动态加载
状态隔离
全局命名空间隔离
编译钩子
嵌套的虚拟化
能够配置默认的模块加载器,而且能够构建新的加载器来评估和加载独立或受限上下文中的代码。
// 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
用于常见算法的高效数据结构。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]
代理使用托管对象可用的所有行为来建立对象。可用于拦截,对象虚拟化,日志记录/分析等
/ 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]
符号启用对象状态的访问控制。符号容许属性被键入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]
在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
许多新的库添加,包括核心数学库,数组转换助手,字符串助手,和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]
为二进制(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]
全反射API将对象的运行时级元操做公开。这其实是代理API的反面,而且容许进行与代理陷阱相同的元操做。对于实现代理尤为有用。
//no code
更多信息:MDN反映 [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect]
调用尾部位置保证不会无限增加堆栈。在无界输入的状况下使递归算法安全。
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]