一、简介
ECMAScript 2015 是在 2015 年 6 月获批的 ECMAScript 标准。对 ECMAScript 来说,ES2015 是一个巨大的更新,第一次这样大的更新是在 2009 年。在主流 JavaScript 引擎中实现 ES2015 中特性的工作目前正在如火如荼地进行。
ES2015 特性
二、ES2015 特性
1、Arrows and Lexical This
Arrows are a function shorthand using the => syntax.
arrows 使用“=>”格式,是一种函数简写。
<code>
// 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 (number of arguments) {
numbers.push(number * 2);
}
return numbers;
};
return example();
}
square(2, 4, 7.5, 8, 11.5, 21); // returns: [4, 8, 15, 16, 23, 42]
</code>
2、Classes(一种语法糖)
ES2015 classes are a simple sugar over the prototype-based OO pattern.
<code>
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();
}
}
</code>
3、Enhanced Object Literals
Object literals are extended to support setting the prototype at construction, shorthand for foo: foo assignments, defining methods and making super calls. Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences.
<code>
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.
<code>['proto']: somethingElse, </code>
// Shorthand for ‘handler: handler’
handler,
// Methods
toString() {
// Super calls
return "d " + super.toString();
},
// Computed (dynamic) property names
[ "prop_" + (() => 42)() ]: 42
};
</code>
4、Template Strings(也是一种语法糖)
Template strings provide syntactic sugar for constructing strings.
<code>
// 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.rawIn ES5 "\n" is a line-feed.
// Construct an HTTP request prefix is used to interpret the replacements and construction
GEThttp://foo.org/bar?a=${a}&b=${b} Content-Type: application/json X-Credentials: ${credentials} { "foo": ${foo}, "bar": ${bar}}
(myOnReadyStateChangeHandler);
</code>
5、Destructuring(解构)
允许模式匹配,支持对象和数组匹配。
<code>
// 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
</code>
6、Default + Rest + Spread
Callee-evaluated default parameter values.
在函数回调中,把数组转换成连续参数
<code>
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
</code>
7、Let + Const
let is the new var. const is single-assignment.
<code>
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";
}
}
</code>
8、Iterators + For..Of
<code>
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);
}
</code>
Iteration is based on these duck-typed interfaces
<code>
interface IteratorResult {
done: boolean;
value: any;
}
interface Iterator {
next(): IteratorResult;
}
interface Iterable {
Symbol.iterator: Iterator
}
</code>
9、Generators
Generators simplify iterator-authoring using function* and yield.
声明为 function* 的函数返回一个 Generator 实例。Generator 是 iterators 的子类型,它包含 next 和 throw 。这使得值可以回滚进 generator. 因此,yield 是返回一个值或扔掉一个值的表达。
<code>
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);
}
interface Generator extends Iterator {
next(value?: any): IteratorResult;
throw(exception: any);
}
</code>
三、深度理解
1、Unicode
<code>
// 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);
}
</code>
2、Modules
<code>
// 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));
// 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));
</code>
3、Module Loaders
babel 默认使用 commonJS
<code>
// 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
</code>
4、Map + Set + WeakMap + WeakSet(面向常用算法/程序的有效数据结构)
<code>
// 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
</code>
5、Proxies
<code>
// 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 :...
}
</code>
6、Symbols
Symbols enable access control for object state. Symbols 可以获取对象状态的控制权。Symbols are a new primitive type. 可选项 name 用来 debug,不是自身属性的一部分。symbol 不是私有的,它们可以通过类似 Object.getOwnPropertySymbols 的特性暴露出来。
<code>
(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
</code>
7、Subclassable Built-ins
In ES2015, built-ins like Array, Date and DOM Elements can be subclassed.
<code>
// User code of Array
subclassclass MyArray extends Array
{
constructor(...args) {
super(...args); }
}
var arr = new MyArray();
arr[1] = 12;
arr.length == 2
</code>
8、Math + Number + String + Object APIs
<code>
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) })
</code>
9、Binary and Octal Literals
Two new numeric literal forms are added for binary (b) and octal (o).
<code>
0b111110111 === 503 // true
0o767 === 503 // true
</code>
10、Promises
Promises are a library for asynchronous programming.
<code>
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)]);
})
</code>
11、Reflect API(对实现 proxy 很有用)
<code>
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
</code>
12、Tail Calls
<code>
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)
</code>
网友评论