ecmascript 6
介绍 (Introduction)
ECMAScript 6, also known as ECMAScript 2015, is the latest version of the ECMAScript standard. ES6 is a significant update to the language, and the first update to the language since ES5 was standardized in 2009. Implementation of these features in major JavaScript engines is underway now.
ECMAScript 6,也称为ECMAScript 2015,是ECMAScript标准的最新版本。 ES6是对该语言的重要更新,这是自2009年对ES5进行标准化以来的第一个语言更新。 目前,正在主要JavaScript引擎中实现这些功能。
See the ES6 standard for full specification of the ECMAScript 6 language.
有关ECMAScript 6语言的完整规范,请参见ES6标准 。
ES6 includes the following new features:
ES6包括以下新功能:
ArrowsClassesEnhanced Object LiteralsTemplate StringsDestructuringDefault + Rest + SpreadLet + ConstIterators + For..OfGeneratorsUnicodeModulesModule LoadersMap + Set + WeakMap + WeakSetProxiesSymbolsSubclassable Built-insMath + Number + String + Array + Object APIsBinary and Octal LiteralsPromisesReflect APITail Calls
ArrowsClassesEnhanced Object LiteralsTemplate StringsDestructuringDefault + Rest + SpreadLet + ConstIterators + For..OfGeneratorsUnicodeModulesModule LoadersMap + Set + WeakMap + WeakSetProxiesSymbolsSubclassable Built-insMath + Number + String + Array + Object APIs二进制和八进制LiteralsPromisesReflect
箭 (Arrows)
Arrows are a function shorthand using the =>
syntax. They are syntactically similar to the related feature in C#, Java 8 and CoffeeScript. They support both statement block bodies as well as expression bodies which return the value of the expression. Unlike functions, arrows share the same lexical this
as their surrounding code.
箭头是使用=>
语法的功能缩写。 它们在语法上类似于C#,Java 8和CoffeeScript中的相关功能。 它们支持语句块主体和返回表达式值的表达式主体。 不同于功能,箭头共享词汇相同this
作为其周围的代码。
// 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));
}
}
More info: MDN Arrow Functions
更多信息: MDN箭头功能
班级 (Classes)
ES6 classes are a simple sugar over the prototype-based OO pattern. Having a single convenient declarative form makes class patterns easier to use, and encourages interoperability. Classes support prototype-based inheritance, super calls, instance and static methods and constructors.
ES6类是对基于原型的OO模式的简单补充。 具有单个方便的声明形式使类模式更易于使用,并鼓励了互操作性。 类支持基于原型的继承,超级调用,实例以及静态方法和构造函数。
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();
}
}
More info: MDN Classes
更多信息: MDN类
增强的对象文字 (Enhanced Object Literals)
Object literals are extended to support setting the prototype at construction, shorthand for foo: foo
assignments, defining methods, making super calls, and computing property names with expressions. Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences.
扩展了对象常量以支持在构造时设置原型, foo: foo
简写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
};
More info: MDN Grammar and types: Object literals
更多信息: MDN语法和类型:对象文字
模板字符串 (Template Strings)
Template strings provide syntactic sugar for constructing strings. This is similar to string interpolation features in Perl, Python and more. Optionally, a tag can be added to allow the string construction to be customized, avoiding injection attacks or constructing higher level data structures from string contents.
模板字符串提供了用于构造字符串的语法糖。 这类似于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);
More info: MDN Template Strings
更多信息: MDN模板字符串
解构 (Destructuring)
Destructuring allows binding using pattern matching, with support for matching arrays and objects. Destructuring is fail-soft, similar to standard object lookup foo["bar"]
, producing undefined
values when not found.
解构允许使用模式匹配进行绑定,并支持匹配数组和对象。 销毁是失败的,类似于标准对象查找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;
More info: MDN Destructuring assignment
更多信息: MDN解构分配
默认+休息+传播 (Default + Rest + Spread)
Callee-evaluated default parameter values. Turn an array into consecutive arguments in a function call. Bind trailing parameters to an array. Rest replaces the need for arguments
and addresses common cases more directly.
被调用方评估的默认参数值。 在函数调用中将数组转换为连续的参数。 将尾随参数绑定到数组。 休息代替了对arguments
的需求,并更直接地解决了常见情况。
function f(x, y=12) {
// y is 12 if not passed (or passed as undefined)
return x + y;
}
f(3) == 15function f(x, ...y) {
// y is an Array
return x * y.length;
}
f(3, "hello", true) == 6function f(x, y, z) {
return x + y + z;
}
// Pass each elem of array as argument
f(...[1,2,3]) == 6
More MDN info: Default parameters, Rest parameters, Spread Operator
让+ const (Let + Const)
Block-scoped binding constructs. let
is the new var
. const
is single-assignment. Static restrictions prevent use before assignment.
块范围绑定结构。 let
是新的var
。 const
是单分配。 静态限制会阻止分配前使用。
function f() {
{
let x;
{
// okay, block scoped name
const x = "sneaky";
// error, const
x = "foo";
}
// error, already declared in block
let x = "inner";
}
}
More MDN info: let statement, const statement
迭代器+ For..Of (Iterators + For..Of)
Iterator objects enable custom iteration like CLR IEnumerable or Java Iterable. Generalize for..in
to custom iterator-based iteration with for..of
. Don’t require realizing an array, enabling lazy design patterns like LINQ.
迭代器对象启用自定义迭代,例如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);
}
Iteration is based on these duck-typed interfaces (using TypeScript type syntax for exposition only):
迭代基于以下鸭子类型的接口(仅对博览会使用TypeScript类型语法):
interface IteratorResult {
done: boolean;
value: any;
}
interface Iterator {
next(): IteratorResult;
}
interface Iterable {
[Symbol.iterator](): Iterator
}
More info: MDN for…of
更多信息: ……的MDN
发电机 (Generators)
Generators simplify iterator-authoring using function*
and yield
. A function declared as function* returns a Generator instance. Generators are subtypes of iterators which include additional next
and throw
. These enable values to flow back into the generator, so yield
is an expression form which returns a value (or throws).
生成器使用function*
和yield
简化了迭代器创作。 声明为function *的函数返回Generator实例。 生成器是迭代器的子类型,包括附加的next
和throw
。 这些使值能够流回到生成器中,因此yield
是一种返回值(或引发)的表达式形式。
Note: Can also be used to enable ‘await’-like async programming, see also ES7 await
proposal.
注意:也可以用于启用类似于“ 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);
}
The generator interface is (using TypeScript type syntax for exposition only):
生成器接口是(仅将TypeScript类型语法用于博览会):
interface Generator extends Iterator {
next(value?: any): IteratorResult;
throw(exception: any);
}
More info: MDN Iteration protocols
更多信息: MDN迭代协议
统一码 (Unicode)
Non-breaking additions to support full Unicode, including new Unicode literal form in strings and new RegExp u
mode to handle code points, as well as new APIs to process strings at the 21bit code points level. These additions support building global apps in JavaScript.
不间断的新增功能支持完整的Unicode,包括字符串中的新Unicode文字形式和用于处理代码点的新RegExp u
模式,以及用于在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);
}
More info: MDN RegExp.prototype.unicode
更多信息: MDN RegExp.prototype.unicode
模组 (Modules)
Language-level support for modules for component definition. Codifies patterns from popular JavaScript module loaders (AMD, CommonJS). Runtime behaviour defined by a host-defined default loader. Implicitly async model — no code executes until requested modules are available and processed.
对组件定义模块的语言级别支持。 整理来自流行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 *
:
其他一些功能包括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);
More MDN info: import statement, export statement
模块装载机 (Module Loaders)
Module loaders support:
模块加载器支持:
- Dynamic loading 动态加载
- State isolation 状态隔离
- Global namespace isolation 全局名称空间隔离
- Compilation hooks 编译挂钩
- Nested virtualization 嵌套虚拟化
The default module loader can be configured, and new loaders can be constructed to evaluate and load code in isolated or constrained contexts.
可以配置默认的模块加载器,并且可以构造新的加载器以在隔离或受约束的上下文中评估和加载代码。
// 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 (Map + Set + WeakMap + WeakSet)
Efficient data structures for common algorithms. WeakMaps provides leak-free object-key’d side tables.
通用算法的高效数据结构。 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
More MDN info: Map, Set, WeakMap, WeakSet
更多MDN信息: Map , Set , WeakMap , WeakSet
代理人 (Proxies)
Proxies enable creation of objects with the full range of behaviors available to host objects. Can be used for interception, object virtualization, logging/profiling, etc.
代理使对象的创建具有可用于宿主对象的全部行为。 可以用于拦截,对象虚拟化,日志记录/分析等。
// 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:...
}
More info: MDN Proxy
更多信息: MDN代理
符号 (Symbols)
Symbols enable access control for object state. Symbols allow properties to be keyed by either string
(as in ES5) or symbol
. Symbols are a new primitive type. Optional description
parameter used in debugging - but is not part of identity. Symbols are unique (like gensym), but not private since they are exposed via reflection features like Object.getOwnPropertySymbols
.
符号启用对对象状态的访问控制。 使用符号可以通过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
More info: MDN Symbol
更多信息: MDN符号
可细分的内置 (Subclassable Built-ins)
In ES6, built-ins like Array
, Date
and DOM Element
s can be subclassed.
在ES6中,可以将Array
, Date
和DOM Element
之类的内置子类化。
Object construction for a function named Ctor
now uses two-phases (both virtually dispatched):
现在,名为Ctor
的函数的对象构造使用两个阶段(实际上都是分派的):
Call
Ctor[@@create]
to allocate the object, installing any special behavior调用
Ctor[@@create]
分配对象,安装任何特殊行为- Invoke constructor on new instance to initialize 在新实例上调用构造函数以进行初始化
The known @@create
symbol is available via Symbol.create
. Built-ins now expose their @@create
explicitly.
可通过Symbol.create
获得已知的@@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
数学+数字+字符串+数组+对象API (Math + Number + String + Array + Object APIs)
Many new library additions, including core Math libraries, Array conversion helpers, String helpers, and Object.assign for copying.
许多新的库添加,包括核心数学库,数组转换帮助器,字符串帮助器和用于复制的Object.assign。
Number.EPSILON
Number.isInteger(Infinity) // false
Number.isNaN("NaN") // falseMath.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) })
More MDN info: Number, Math, Array.from, Array.of, Array.prototype.copyWithin, Object.assign
更多MDN信息: Number , Math , Array.from , Array.of , Array.prototype.copyWithin , Object.assign
二进制和八进制文字 (Binary and Octal Literals)
Two new numeric literal forms are added for binary (b
) and octal (o
).
为二进制( b
)和八进制( o
)添加了两个新的数字文字形式。
0b111110111 === 503 // true
0o767 === 503 // true
承诺 (Promises)
Promises are a library for asynchronous programming. Promises are a first class representation of a value that may be made available in the future. Promises are used in many existing JavaScript libraries.
承诺是用于异步编程的库。 承诺是将来可能提供的值的一流表示。 在许多现有JavaScript库中都使用了Promise。
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)]);
})
More info: MDN Promise
更多信息: MDN承诺
反映API (Reflect API)
Full reflection API exposing the runtime-level meta-operations on objects. This is effectively the inverse of the Proxy API, and allows making calls corresponding to the same meta-operations as the proxy traps. Especially useful for implementing proxies.
全反射API公开了对象上的运行时级别的元操作。 这实际上是代理API的逆,并且允许进行与代理陷阱相同的元操作所对应的调用。 对于实现代理尤其有用。
// No sample yet
More info: MDN Reflect
更多信息: MDN Reflect
尾叫 (Tail Calls)
Calls in tail-position are guaranteed to not grow the stack unboundedly. Makes recursive algorithms safe in the face of unbounded inputs.
确保尾部位置的调用不会无限制地增加堆栈。 面对无限输入,使递归算法安全。
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://medium.com/@umair.aslam919/ecmascript-6-69e42924370c
ecmascript 6