ES2015 (ES6) 新特性

http://babeljs.io/docs/learn-es2015/

Learn ES2015

A detailed overview of ECMAScript 2015 features. Based on Luke Hoban's es6features repo.

Edit this page

es6features

This document was originally taken from Luke Hoban's excellent es6features repo. Go give it a star on GitHub!

REPL

Be sure to try these features out in the online REPL.

1

Introduction

ECMAScript 2015 is the newest version of the ECMAScript standard. This standard was ratified in June 2015. ES2015 is a significant update to the language, and the first major update to the language since ES5 was standardized in 2009. Implementation of these features in major JavaScript engines is underway now.

See the ES2015 standard for full specification of the ECMAScript 2015 language.

ECMAScript 2015 Features

  1. Arrows and Lexical This

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 expression and statement bodies. Unlike functions, arrows share the same lexical this as their surrounding 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)); } };

  1. Classes

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

  1. class SkinnedMesh extends THREE.Mesh {
  2. constructor(geometry, materials) {
  3. super(geometry, materials);
  4. this.idMatrix = SkinnedMesh.defaultMatrix();
  5. this.bones = [];
  6. this.boneMatrices = [];
  7. //...
  8. }
  9. update(camera) {
  10. //...
  11. super.update();
  12. }
  13. static defaultMatrix() {
  14. return new THREE.Matrix4();
  15. }
  16. }
  1. 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.

  1. var obj = {
  2. // Sets the prototype. "__proto__" or '__proto__' would also work.
  3. __proto__: theProtoObj,
  4. // Computed property name does not set prototype or trigger early error for
  5. // duplicate __proto__ properties.
  6. ['__proto__']: somethingElse,
  7. // Shorthand for ‘handler: handler’
  8. handler,
  9. // Methods
  10. toString() {
  11. // Super calls
  12. return "d " + super.toString();
  13. },
  14. // Computed (dynamic) property names
  15. [ "prop_" + (() => 42)() ]: 42
  16. };

The __proto__ property requires native support, and was deprecated in previous ECMAScript versions. Most engines now support the property, but some do not. Also, note that only web browsers are required to implement it, as it's in Annex B. It is available in Node.

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

  1. // Basic literal string creation
  2. `This is a pretty little template string.`
  3. // Multiline strings
  4. `In ES5 this is
  5. not legal.`
  6. // Interpolate variable bindings
  7. var name = "Bob", time = "today";
  8. `Hello ${name}, how are you ${time}?`
  9. // Unescaped template strings
  10. String.raw`In ES5 "\n" is a line-feed.`
  11. // Construct an HTTP request prefix is used to interpret the replacements and construction
  12. GET`http://foo.org/bar?a=${a}&b=${b}
  13. Content-Type: application/json
  14. X-Credentials: ${credentials}
  15. { "foo": ${foo},
  16. "bar": ${bar}}`(myOnReadyStateChangeHandler);

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.

  1. // list matching
  2. var [a, ,b] = [1,2,3];
  3. a === 1;
  4. b === 3;
  5. // object matching
  6. var { op: a, lhs: { op: b }, rhs: c }
  7. = getASTNode()
  8. // object matching shorthand
  9. // binds `op`, `lhs` and `rhs` in scope
  10. var {op, lhs, rhs} = getASTNode()
  11. // Can be used in parameter position
  12. function g({name: x}) {
  13. console.log(x);
  14. }
  15. g({name: 5})
  16. // Fail-soft destructuring
  17. var [a] = [];
  18. a === undefined;
  19. // Fail-soft destructuring with defaults
  20. var [a = 1] = [];
  21. a === 1;
  22. // Destructuring + defaults arguments
  23. function r({x, y, w = 10, h = 10}) {
  24. return x + y + w + h;
  25. }
  26. r({x:1, y:2}) === 23
  1. 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.

  1. function f(x, y=12) {
  2. // y is 12 if not passed (or passed as undefined)
  3. return x + y;
  4. }
  5. f(3) == 15
  1. function f(x, ...y) {
  2. // y is an Array
  3. return x * y.length;
  4. }
  5. f(3, "hello", true) == 6
  1. function f(x, y, z) {
  2. return x + y + z;
  3. }
  4. // Pass each elem of array as argument
  5. f(...[1,2,3]) == 6
  • Let + Const

Block-scoped binding constructs. let is the new varconst is single-assignment. Static restrictions prevent use before assignment.

  1. function f() {
  2. {
  3. let x;
  4. {
  5. // okay, block scoped name
  6. const x = "sneaky";
  7. // error, const
  8. x = "foo";
  9. }
  10. // okay, declared with `let`
  11. x = "bar";
  12. // error, already declared in block
  13. let x = "inner";
  14. }
  15. }
  • 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.

  1. let fibonacci = {
  2. [Symbol.iterator]() {
  3. let pre = 0, cur = 1;
  4. return {
  5. next() {
  6. [pre, cur] = [cur, pre + cur];
  7. return { done: false, value: cur }
  8. }
  9. }
  10. }
  11. }
  12. for (var n of fibonacci) {
  13. // truncate the sequence at 1000
  14. if (n > 1000)
  15. break;
  16. console.log(n);
  17. }

Iteration is based on these duck-typed interfaces (using TypeScript type syntax for exposition only):

  1. interface IteratorResult {
  2. done: boolean;
  3. value: any;
  4. }
  5. interface Iterator {
  6. next(): IteratorResult;
  7. }
  8. interface Iterable {
  9. [Symbol.iterator](): Iterator
  10. }

Support via polyfill

In order to use Iterators you must include the Babel polyfill.

  • 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).

Note: Can also be used to enable ‘await’-like async programming, see also ES7 await proposal.

  1. var fibonacci = {
  2. [Symbol.iterator]: function*() {
  3. var pre = 0, cur = 1;
  4. for (;;) {
  5. var temp = pre;
  6. pre = cur;
  7. cur += temp;
  8. yield cur;
  9. }
  10. }
  11. }
  12. for (var n of fibonacci) {
  13. // truncate the sequence at 1000
  14. if (n > 1000)
  15. break;
  16. console.log(n);
  17. }

The generator interface is (using TypeScript type syntax for exposition only):

  1. interface Generator extends Iterator {
  2. next(value?: any): IteratorResult;
  3. throw(exception: any);
  4. }

Support via polyfill

In order to use Generators you must include the Babel polyfill.

  • Comprehensions

Removed in Babel 6.0

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.

  1. // same as ES5.1
  2. "
  3. ES2015 (ES6) 新特性: 20 个的更多相关文章

      1. ES6新特性简介
      1. ES6新特性简介 环境安装 npm install -g babel npm install -g babel-node //提供基于node的REPL环境 //创建 .babelrc 文件 {&qu ...

      1. ES6新特性概览
      1. 本文基于lukehoban/es6features ,同时参考了大量博客资料,具体见文末引用. ES6(ECMAScript 6)是即将到来的新版本JavaScript语言的标准,代号harmony( ...

      1. ES6新特性之模板字符串
      1. ES6新特性概览  http://www.cnblogs.com/Wayou/p/es6_new_features.html 深入浅出ES6(四):模板字符串   http://www.infoq.c ...

      1. Atitit js版本es5 es6新特性
      1. Atitit js版本es5 es6新特性 Es5( es5 其实就是adobe action script的标准化)1 es6新特性1 Es5( es5 其实就是adobe action scrip ...

      1. ES6新特性:Proxy代理器
      1. ES6新特性:Proxy: 要使用的话, 直接在浏览器中执行即可, node和babel目前还没有Proxy的polyfill;,要使用的话,直接在浏览器中运行就好了, 浏览器的兼容性为:chrome ...

      1. ES6新特性(函数默认参数,箭头函数)
      1. ES6新特性之 函数参数的默认值写法 和 箭头函数. 1.函数参数的默认值 ES5中不能直接为函数的参数指定默认值,只能通过以下的变通方式:   从上面的代码可以看出存在一个问题,当传入的参数为0或者 ...

      1. 轻松学会ES6新特性之生成器
      1. 生成器虽然是ES6最具魔性的新特性,但也是最难懂得的一节,笔者写了大量的实例来具体化这种抽象的概念,能够让人一看就懂,目的是希望别人不要重复或者减少笔者学习生成器的痛苦经历. 在说具体的ES6生成器之 ...

      1. 必须掌握的ES6新特性
      1. ES6(ECMAScript2015)的出现,让前端开发者收到一份惊喜,它简洁的新语法.强大的新特性,带给我们更便捷和顺畅的编码体验,赞! 以下是ES6排名前十的最佳特性列表(排名不分先后): 1.D ...

      1. 你不知道的JavaScript--Item24 ES6新特性概览
      1. ES6新特性概览 本文基于lukehoban/es6features ,同时参考了大量博客资料,具体见文末引用. ES6(ECMAScript 6)是即将到来的新版本JavaScript语言的标准,代 ...

    1. 随机推荐

        1. 华为交换机telnet登录时老是提醒是否更改初始密码- Warning: The initial password poses security risks
        1. 问题:华为交换机在Telnet登录的时候总是提示初始密码不安全需要修改密码的处理方法 Warning: The initial password poses security risks   如果你输 ...

        1. MySQL调优性能监控之performance schema
        1. 一.performance_schema的介绍 performance:性能 schema:图(表)示,以大纲或模型的形式表示计划或理论. MySQL的performance schema 用于监控M ...

        1. 电脑打不开gitHub的解决方法
        1. 电脑打不开gitHub的解决方法 方法:修改本地的hosts文件 因为Github是国外网站,所以经常会遇到打不开的问题,并且有时能打开但是网速好慢 解决这个问题的方法是 :   C:\Windows ...

        1. new() 和 make() 的区别 var arr1 = new([5]int) var arr2 [5]int
        1. Effective Go - The Go Programming Language https://golang.org/doc/effective_go.html#allocation_new A ...

        1. C++ Primer Plus读书笔记(二)处理数据
        1. 1.格式化输出: 和C语言不太一样,C++格式化输出进制格式如下: 1 int a = 42; 2 int b = 42; 3 int c = 42; 4 5 cout << a < ...

        1. Communicating sequential processes CSP 通信顺序进程 CSP writing to a file by name (process, Erlang) vs. writing to a file descriptor (channel, Go)
        1. the-way-to-go_ZH_CN/01.2.md at master · Unknwon/the-way-to-go_ZH_CN https://github.com/Unknwon/the-w ...

        1. Flash 终将谢幕:微软将于年底( 2020 年 )停止对 Flash 的支持
        1. 近日,微软宣布将于今年 12 月终止对 Adobe Flash Player 的支持,届时,微软旗下所有浏览器都将无法使用 Flash,Adobe 也不会在今年 12 月后发布安全更新.早在 2017 ...

        1. Spring听课笔记(专题二下)
        1. 第4章 Spring Bean基于注解的装配 4.1 Bean的定义及作用域的注解实现 1. Bean定义的注解 -- @Component是一个通用注解,可用于任何bean -- @Reposito ...

        1. Prometheus+Grafana通过kafka_exporter监控kafka
        1. Prometheus+Grafana通过kafka_exporter监控kafka 一.暴露 kafka-metric 方式 二.jmx_exporter方式 2.1 下载jmx_prometheus ...

        1. python模块----optparse模块、argparse模块 (命令行解析模块)
        1. 简介 optparse module---自版本3.2以来已弃用:optparse模块已弃用,将不再进一步开发:将继续使用argparse模块进行开发.optparse使用一种更具声明性的命令行解析方 ...