v>

学习es6

ECMAScript 2015功能的详细概述。基于卢克·霍本的e6features回购。

0.0.1. 本文是google 自动翻译

1. 介绍

ECMAScript 2015是2015年6月批准的ECMAScript标准。

ES2015是语言的重要更新,自2009年ES5标准化以来语言的第一次重大更新。主要JavaScript引擎中的这些功能的实现正在进行中

有关ECMAScript 2015语言的完整规范,请参阅ES2015标准

2. ECMAScript 2015功能

2.1. 箭头和词汇这个

箭头是使用=>语法的缩写。它们在语法上类似于C#,Java 8和CoffeeScript中的相关功能。他们支持表达和声明机构。与函数不同,箭头this与其周围的代码共享相同的词法。如果一个箭头在另一个函数内,它将共享其父函数的“arguments”变量。

// 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]

 

2.2. 类

ES2015课程是基于原型的OO模式的简单糖。拥有单一的方便的声明式表单使得类模式更易于使用,并鼓励互操作性。类支持基于原型的继承,超级调用,实例和静态方法和构造函数。

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();
  }
}

 

2.3. 增强的对象文字

扩展了对象文字,以支持在构建中设计原型,foo: foo分配简写,定义方法和进行超级调用。总而言之,这些也使对象文字和类声明更加紧密,让基于对象的设计也受益于一些相同的便利。

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版本中已被弃用。大多数引擎现在支持该属性,但有些则不支持。另外请注意,只有Web浏览器才能实现它,如附件B所示。它在Node中可用。

2.4. 模板字符串

模板字符串提供构造字符串的语法糖。这与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);

 

2.5. 解构

解构允许使用模式匹配进行绑定,并支持匹配的数组和对象。破坏是失败软件,类似于标准对象查找foo["bar"]undefined当找不到时生成值。

// 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

 

2.6. 默认+休息+传播

Callee评估的默认参数值。将数组转换为函数调用中的连续参数。将后跟参数绑定到数组。休息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

 

2.7. 让+ Const

块结合结构。let是新的varconst是单独分配。静态限制在分配前禁止使用。

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";
  }
}

 

2.8. 迭代器+ For..Of

迭代器对象启用自定义迭代,如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);
}

 

迭代基于这些鸭型接口(仅使用TypeScript类型语法):

interface IteratorResult {
  done: boolean;
  value: any;
}
interface Iterator {
  next(): IteratorResult;
}
interface Iterable {
  [Symbol.iterator](): Iterator
}

 

2.8.1. 通过polyfill支持

为了使用迭代器,您必须包括Babel polyfill

2.9. 发电机

发电机使用function*和简化迭代器创作yield。声明为function *的函数返回一个Generator实例。发生器是迭代器的子类型,其包括附加nextthrow。这些使值返回到生成器中,所以yield返回值(或throws)的表达式形式也是如此。

注意:也可以用来启用“等待”的异步编程,另请参阅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);
}

 

2.9.1. 通过polyfill支持

为了使用发电机,您必须包括Babel polyfill

2.10. 推导

在Babel 6.0中删除

2.11. 统一

支持完整Unicode u的不间断补充,包括字符串中的新unicode文字形式和处理代码点的新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);
}

 

2.12. 模块

组件定义模块的语言级支持。编辑流行的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 defaultexport *

// 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));

 

2.12.1. 模块格式化器

Babel可以将ES2015模块转换成几种不同的格式,包括Common.js,AMD,System和UMD。你甚至可以创建自己的。有关详细信息,请参阅模块文档

2.13. 模块装载机

2.13.1. 不是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

 

2.13.2. 需要额外的聚合物填充

由于Babel默认使用common.js模块,它不包括模块加载程序API的polyfill。得到它在这里

2.13.3. 使用模块装载机

为了使用这个,你需要告诉Babel使用system模块格式化程序。另请务必查看System.js

2.14. 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

 

2.14.1. 通过polyfill支持

为了在所有环境中支持“地图”,“集合”,“WeakMaps”和“WeakSets”,您必须包括Babel polyfill

2.15. 代理

代理可以创建具有可用于托管对象的全部行为的对象。可用于拦截,对象虚拟化,日志/分析等。

// 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 :...
}

 

2.15.1. 不支持的功能

由于ES5的限制,代理不能被淹没或多重填充。请参阅各种JavaScript引擎的支持。

2.16. 符号

符号允许对象状态的访问控制。符号允许属性由string(如ES5)或symbol。符号是一种新的原始类型。name在调试中使用的可选参数 - 但不是身份的一部分。符号是独特的(如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

 

2.16.1. 有限的支持通过polyfill

有限的支持需要Babel polyfill。由于语言限制,某些功能不能被淹没或多重填充。有关详细信息,请参阅core.js的注意事项部分

2.17. 次级内置

在ES2015中,内置的ArrayDate和DOM Element可以被子类化。

// User code of Array subclass
class MyArray extends Array {
    constructor(...args) { super(...args); }
}

var arr = new MyArray();
arr[1] = 12;
arr.length == 2

 

2.17.1. 部分支持

内置的子类可以根据具体情况进行评估,因为类HTMLElement 可以被子类化,而许多例如DateArray并且Error 不能由于ES5引擎限制。

2.18. Math + Number + String + Object API

许多新的库增加,包括核心数学库,数组转换助手和用于复制的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) })

 

2.18.1. 有限的支持从polyfill

这些API大部分都是由Babel polyfill支持的。然而,由于各种原因(例如String.prototype.normalize需要大量附加代码来支持),某些功能被省略。您可以在这里找到更多的聚合物。

2.19. 二进制和八进制文字

为binary(b)和octal(o)添加了两个新的数字文字形式。

0b111110111 === 503 // true
0o767 === 503 // true

 

2.19.1. 只支持文字形式

巴别只能转变0o767而不是Number("0o767")

2.20. 承诺

承诺是用于异步编程的库。承诺是将来可能提供的价值的第一类代表。许多现有的JavaScript库都使用Promises。

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)]);
})

 

2.20.1. 通过polyfill支持

为了支持Promises,您必须包括Babel polyfill

2.21. 反映API

全反射API暴露了对象的运行时级元操作。这实际上是代理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

 

2.21.1. 通过polyfill支持

为了使用Reflect API,您必须包括Babel polyfill

2.22. 尾呼

尾部的呼叫保证不会无限制地增长堆栈。使递归算法面对无界输入时的安全。

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)

 

posted @ 2018-11-06 11:06  一小半  阅读(328)  评论(0编辑  收藏  举报