ECMAScript 6 git.io/es6features
ECMAScript 6, 又叫做ECMAScript 2015, 是最新版本的Script标准。ES6是Javascript语言的巨大改进,也是自2009年后发布ES5标准版本后的首次更新。 这些新特性在各大JavaScript中的实现可以在 underway now中找到。
在这里可以看到ES6的详细说明 ES6 standard ES6 包括以下特征:
- arrows
- classes
- enhanced object literals
- template strings
- destructuring
- default + rest + spread
- let + const
- iterators + for..of
- generators
- unicode
- modules
- module loaders
- map + set + weakmap + weakset
- proxies
- symbols
- subclassable built-ins
- promises
- math + number + string + array + object APIs
- binary and octal literals
- reflect api
- tail calls
箭头就是使用=>
语法表示的函数简写。 它在结构上类似C#,Java 8和CoffeeScript。他支持声明式结构和含有返回值的表达式。与函数不同的是,箭头内的'this'与箭头周围的代码一致(译者注: 相当于帮你省掉了bind(this))。
// 表达式写法(有返回值)
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}));
// 声明式写法(有返回值)
nums.forEach(v => {
if (v % 5 === 0)
fives.push(v);
});
// this
var bob = {
_name: "Bob",
_friends: [],
printFriends() {
this._friends.forEach(f =>
console.log(this._name + " knows " + f));
}
}
ES6的类式面向对象模型的单糖。有表单声明使得它更好用也更好交互。类支持继承模型,父继承,实例,静态方法和构造函数。
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();
}
}
对象按照字面意思是支持原型构造比如‘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
};
字符串模板提供字符串构造的语法糖。它类似于字符串在其他语言中的用法,如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);
解构同意捆绑通过模式匹配,可以匹配数组和对象。像‘foo["bar"]’这样找不到属性值时产生‘未定义’值,而不会导致致命的错误。
// 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;
设置默认参数值。在函数调用时将数组转化为连续的参数。将尾参数绑定数组。免去了参数和更加直接的地址传递。
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’是新的数据变量。‘const’是单赋值。静态在赋值前不能使用。
Block-scoped binding constructs. let
is the new var
. const
is single-assignment. Static restrictions prevent use before assignment.
function f() {
{
let x;
{
// okay, block scoped name
const x = "sneaky";
// error, const
x = "foo";
}
// error, already declared in block
let x = "inner";
}
}
迭代器类似CLR IEnumerable或者java迭代器。 将‘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);
}
迭代时基于鸭子类型的接口。
interface IteratorResult {
done: boolean;
value: any;
}
interface Iterator {
next(): IteratorResult;
}
interface Iterable {
[Symbol.iterator](): Iterator
}
代码生产器通过‘function*’,'yield'简化了迭代器的操作。当函数声明为function*就返回一个代码生成器。生成器是迭代器的子类型包含‘next’,'throw'.这使得只能够流回生成器,所以‘yield’是一个表达式它返回一个值。
代码生成器也可以在异步中使用。
Note: Can also be used to enable ‘await’-like async programming, see also ES7 await
proposal.
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);
}
The generator interface is (using TypeScript type syntax for exposition only):
interface Generator extends Iterator {
next(value?: any): IteratorResult;
throw(exception: any);
}
不断地有其他方式支持完整编码,包括在字符串中的文字形式的编码和‘u’模式的代码处理以及新的APIs以21位字符编码处理字符串。这些方式在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";
alert("2π = " + math.sum(math.pi, math.pi));
// otherApp.js
import {sum, pi} from "lib/math";
alert("2π = " + sum(pi, pi));
Some additional features include export default
and 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);
模块导入需要:动态装载,状态独立,独立的全局命名空间,编译中断,虚拟化
可以配置默认装载模块,并且新的装在器可以构在独立的或者指定的环境中建值和代码
// 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
代理可以用一系列的行为在主机创建对象。可以用在拦截,对象虚拟化,编译等。
// 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';
There are traps available for all of the runtime-level meta-operations:
var handler =
{
get:...,
set:...,
has:...,
deleteProperty:...,
apply:...,
construct:...,
getOwnPropertyDescriptor:...,
defineProperty:...,
getPrototypeOf:...,
setPrototypeOf:...,
enumerate:...,
ownKeys:...,
preventExtensions:...,
isExtensible:...
}
符号提供控制对象状态的入口。符号既可以是字符串也可以是符号。符号是一个新的私有类型。在调试中可以选择描述参数但它并不是主键。符号是唯一的但它不是私有的因为他们通过调用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
在ES6中,数组,数据和DOM中的元素可以是子类。对象的构建函数叫‘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是新的外部库,包括数学库,数组转变助手,字符串助手和对象的拷贝。
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) })
八进制的数以‘o’开头,二进制的数以‘b’开头。
Two new numeric literal forms are added for binary (b
) and octal (o
).
0b111110111 === 503 // true
0o767 === 503 // true
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)]);
})
完整的reflection API将运行级上的元操作在对象上展示出来。这是对代理接口的反转,同时也允许相同元操作间有联系(作为代理陷阱)。尤其在不熟代理时十分有用。
// No sample yet
TailCalls就是在尾部的位置调用以保证不会超出堆栈的界限。让递归算法在面对没有界限的输入时更安全。
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)