UDN-企业互联网技术人气社区

板块导航

浏览  : 700
回复  : 0

[干货] ECMAScript 6的新特性

[复制链接]
弑杀天下的头像 楼主
发表于 2015-12-21 22:23:41 | 显示全部楼层 |阅读模式

  Introduction
 
  ECMAScript 6, also known as ECMAScript 2015, is the upcoming version of the ECMAScript standard. This standard is targeting ratification in June 2015. 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.

  See the draft ES6 standard for full specification of the ECMAScript 6 language.

  ES6 includes the following new features:

  1. arrows
  2. classes
  3. enhanced object literals
  4. template strings
  5. destructuring
  6. default + rest + spread
  7. let + const
  8. iterators + for..of
  9. generators
  10. unicode
  11. modules
  12. module loaders
  13. map + set + weakmap + weakset
  14. proxies
  15. symbols
  16. subclassable built-ins
  17. promises
  18. math + number + string + array + object APIs
  19. binary and octal literals
  20. reflect api
  21. tail calls
  22. ECMAScript 6 Features
复制代码


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

  1. // Expression bodies
  2. var odds = evens.map(v => v + 1);
  3. var nums = evens.map((v, i) => v + i);
  4. var pairs = evens.map(v => ({even: v, odd: v + 1}));

  5. // Statement bodies
  6. nums.forEach(v => {
  7.   if (v % 5 === 0)
  8.     fives.push(v);
  9. });

  10. // Lexical this
  11. var bob = {
  12.   _name: "Bob",
  13.   _friends: [],
  14.   printFriends() {
  15.     this._friends.forEach(f =>
  16.       console.log(this._name + " knows " + f));
  17.   }
  18. }
复制代码


  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.

  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.   get boneCount() {
  14.     return this.bones.length;
  15.   }
  16.   set matrixType(matrixType) {
  17.     this.idMatrix = SkinnedMesh[matrixType]();
  18.   }
  19.   static defaultMatrix() {
  20.     return new THREE.Matrix4();
  21.   }
  22. }
复制代码


  Enhanced Object Literals

  Object literals are extended to support setting the prototype at construction, shorthand for foo: fooassignments, 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.

  1. var obj = {
  2.     // __proto__
  3.     __proto__: theProtoObj,
  4.     // Shorthand for ‘handler: handler’
  5.     handler,
  6.     // Methods
  7.     toString() {
  8.      // Super calls
  9.      return "d " + super.toString();
  10.     },
  11.     // Computed (dynamic) property names
  12.     [ 'prop_' + (() => 42)() ]: 42
  13. };
复制代码


  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. `In JavaScript '\n' is a line-feed.`

  3. // Multiline strings
  4. `In JavaScript this is
  5. not legal.`

  6. // String interpolation
  7. var name = "Bob", time = "today";
  8. `Hello ${name}, how are you ${time}?`

  9. // Construct an HTTP request prefix is used to interpret the replacements and construction
  10. GET`http://foo.org/bar?a=${a}&b=${b}
  11.     Content-Type: application/json
  12.     X-Credentials: ${credentials}
  13.     { "foo": ${foo},
  14.       "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 undefinedvalues when not found.

  1. // list matching
  2. var [a, , b] = [1,2,3];

  3. // object matching
  4. var { op: a, lhs: { op: b }, rhs: c }
  5.        = getASTNode()

  6. // object matching shorthand
  7. // binds `op`, `lhs` and `rhs` in scope
  8. var {op, lhs, rhs} = getASTNode()

  9. // Can be used in parameter position
  10. function g({name: x}) {
  11.   console.log(x);
  12. }
  13. g({name: 5})

  14. // Fail-soft destructuring
  15. var [a] = [];
  16. a === undefined;

  17. // Fail-soft destructuring with defaults
  18. var [a = 1] = [];
  19. a === 1;
  20. 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
  6. function f(x, ...y) {
  7.   // y is an Array
  8.   return x * y.length;
  9. }
  10. f(3, "hello", true) == 6
  11. function f(x, y, z) {
  12.   return x + y + z;
  13. }
  14. // Pass each elem of array as argument
  15. f(...[1,2,3]) == 6
  16. Let + Const
复制代码


  Block-scoped binding constructs. let is the new var. const 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.     // error, already declared in block
  11.     let x = "inner";
  12.   }
  13. }
复制代码


  Iterators + For..Of

  Iterator objects enable custom iteration like CLR IEnumerable or Java Iterable. Generalize for..into 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. }
  18. Iteration is based on these duck-typed interfaces (using TypeScript type syntax for exposition only):

  19. interface IteratorResult {
  20.   done: boolean;
  21.   value: any;
  22. }
  23. interface Iterator {
  24.   next(): IteratorResult;
  25. }
  26. interface Iterable {
  27.   [Symbol.iterator](): Iterator
  28. }
复制代码


  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 andthrow. 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. }
复制代码


  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. "
复制代码
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关于我们
联系我们
  • 电话:010-86393388
  • 邮件:udn@yonyou.com
  • 地址:北京市海淀区北清路68号
移动客户端下载
关注我们
  • 微信公众号:yonyouudn
  • 扫描右侧二维码关注我们
  • 专注企业互联网的技术社区
版权所有:用友网络科技股份有限公司82041 京ICP备05007539号-11 京公网网备安1101080209224 Powered by Discuz!
快速回复 返回列表 返回顶部