[关闭]
@wh1100717 2015-02-02T05:32:12.000000Z 字数 6407 阅读 509

ECMAScript 6 (一)

ECMAScript 数据大学


介绍

ECMAScript 6 是 ECMAScript 标准即将到来的版本。该标准计划于2015年7月批准并实施。相比于在2009年更新的ES5标准,ES6对Javascript语言进行了一系列非常重要的更新。主要的js引擎对标准中的新特性的实现已经在进行中了。

想要查看ES6全部的新特性描述点击 这里

大部分内容来自于 es6features

ES6 包含以下新特性:

尝试ECMAScript 6

目前现代浏览器部分支持ES6特性,如果想进行测试,可以使用以下方式:

ECMAScript 6 特性

Arrows 箭头函数

Arrows 实际上使用 => 对函数书写进行了简化。语法上与C#, Java 8 和 CoffeeScript 类似。

需要注意的是:

  1. arr = [1,2,3,4,5,6,7,8,9,10,11]
  2. arr1 = arr.map(n => n + 1)
  3. console.log(arr1); // [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ]
  4. five = [];
  5. arr.forEach(v => {
  6. if(v % 5 === 0){
  7. five.push(v);
  8. }
  9. });
  10. console.log(five); //[5, 10,15]
  11. //Lexical this
  12. var bob = {
  13. _name: "Bob",
  14. _friends: [],
  15. printFriends() {
  16. this._friends.forEach(f => console.log(this._name + " knows " + f));
  17. }
  18. }
  19. bob._friends.push("Eric");
  20. bob.printFriends() //Bob knows Eric

Classes 类

ES6 的 classes 是基于原型的OO(面向对象)模式的简单语法糖封装。现在提供原生的Class支持后,对象的创建,继承更加直观了,并且父类方法的调用,实例化,静态方法和构造函数等概念都更加形象化。

  1. //Person类
  2. class Person {
  3. //构造器
  4. constructor(name){
  5. this.name = name;
  6. }
  7. //实例方法
  8. sayHi(){
  9. console.log("Hi, this is ", this.name);
  10. }
  11. }
  12. var eric = new Person("Eric Wang");
  13. eric.sayHi(); //Hi, this is Eric Wang
  14. //类的继承
  15. class Engineer extends Person {
  16. constructor(name, position) {
  17. super(name);
  18. this.position = position;
  19. }
  20. introduceWork() {
  21. console.log("I'm doing the ", this.position, " engineer work.")
  22. }
  23. }
  24. var xiaxing = new Engineer("Xia Xing", "Software");
  25. xiaxing.sayHi(); // Hi, this is Xia Xing
  26. xiaxing.introduceWork(); //I'm doing the Software engineer work.

Enhanced object literals 增强的对象字面量

对象字面量被扩展为可以支持对象定义时进行设置原型,定义方法和调用富函数。

  1. var person = {
  2. __proto__: {
  3. eat(){
  4. console.log("eat something!");
  5. },
  6. sleep(){
  7. console.log("sleep at night~");
  8. }
  9. },
  10. work(){
  11. console.log("working....");
  12. }
  13. }
  14. person.eat() //eat something!
  15. person.sleep() //sleep at night~
  16. person.work() //working...

Template String 模板字符串/字符串插值

模板字符串提供了构造字符串的语法糖,其与Perl, Python, Coffeescript中的语法类似。通过反引号`来构造具有插值功能的字符串,其中可以包含以${expression/variable}构造的表达式或变量。

  1. // 基本的字符串构建
  2. `In JavaScript '\n' is a line-feed.`
  3. // 多行字符串构建
  4. `In JavaScript this is
  5. not legal.`
  6. // 创建一个差值字符串
  7. var name = "Bob", time = "today";
  8. `Hello ${name}, how are you ${time}?`

Destructuring 解构

支持对数组和对象的绑定进行模式匹配,并自动解析其中的值。解构具有类似于对象查询(foo["bar"],如果值不存在则返回undefined)的容错模式。

  1. //数组匹配
  2. var [a,,b] = [1,2,3];
  3. console.log(a, b); //1 3
  4. // 对象匹配
  5. var {b:b, c:c, d:d} = {
  6. b: {name: "Eric"},
  7. c: [1,2,3],
  8. d: function(x){return x+1;}
  9. }
  10. console.log({}.toString.call(b), b.name);
  11. console.log({}.toString.call(c), c[1]);
  12. console.log({}.toString.call(d), d(10));
  13. // 也可以用于函数传参中
  14. var g = ({name: x}) => console.log(x);
  15. g({name: "Eric"})
  16. // Fail-soft destructuring 容错解构
  17. var [a] = [];
  18. console.log(a === undefined); //true
  19. // Fail-soft with default 带默认值的容错解构
  20. var [a = 1] = [];
  21. console.log(a === 1); //true

Default + Rest + Spread 默认参数,不定参数,扩展参数

  1. //默认参数值
  2. var f1 = (x, y=12) => x + y
  3. console.log(f1(3)) // 15
  4. console.log(f1(3, 4)) // 7
  5. //不定参数
  6. var f2 = (x, ...y) => x * y.length
  7. console.log(f2(3), f2(3,1), f2(3,1,"1",true)) //0 3 9
  8. //扩展参数
  9. var f3 = (x, y, z) => x + y + z
  10. console.log(f3(...[1,2,3])) //6

let + Const 关键字

const为常量,一旦定义不可修改其值,也不可重复定义。

let可以看做块域内的var,区别在其作用域为代码块,并且不能重复定义。

  1. let i = 1111
  2. for (let i=0;i<2;i++)console.log(i);//输出: 0,1
  3. console.log(i); //输出:1111
  4. let i = 2222; //Error: Duplicate declaration, i

如果变量没有在外层定义,则会去寻找代码区块中是否已经定义对应变量。

  1. for (let i=0;i<2;i++)console.log(i);//输出: 0,1
  2. console.log(i);//输出:2

For..Of

我们通过for infor of的实践来快速了解其功能。

除此之外,for of 还可以用在迭代器中。

  1. var items = [10,11,12,13]
  2. for (index in items) {
  3. console.log(index) //输出0,1,2,3
  4. }
  5. for (value of items) {
  6. console.log(value) //输出10,11,12,13
  7. }

Iterator, Generator

Generator深入学习可以参考以下文档:

Unicode

ES6 完整支持Unicode编码。

  1. // same as ES5.1
  2. "𠮷".length == 2
  3. // new RegExp behaviour, opt-in ‘u’
  4. "𠮷".match(/./u)[0].length == 2
  5. // new form
  6. "\u{20BB7}"=="𠮷"=="\uD842\uDFB7"
  7. // new String ops
  8. "𠮷".codePointAt(0) == 0x20BB7
  9. // for-of iterates code points
  10. for(var c of "𠮷") {
  11. console.log(c);
  12. }

Modules 模块

  1. // lib/math.js
  2. export function sum(x, y) {
  3. return x + y;
  4. }
  5. export var pi = 3.141593;
  1. // app.js
  2. import * as math from "lib/math";
  3. alert("2π = " + math.sum(math.pi, math.pi));
  1. // otherApp.js
  2. import {sum, pi} from "lib/math";
  3. alert("2π = " + sum(pi, pi));

export defaultexport * 的使用方式

  1. // lib/mathplusplus.js
  2. export * from "lib/math";
  3. export var e = 2.71828182846;
  4. export default function(x) {
  5. return Math.exp(x);
  6. }
  1. // app.js
  2. import exp, {pi, e} from "lib/mathplusplus";
  3. alert("2π = " + exp(pi, e));

Module Loaders 模块加载器

默认的模块加载器可以被配置,也可以构建新的加载器来加载隔离的代码或者受限制的上下文。

  1. // Dynamic loading – ‘System’ is default loader
  2. System.import('lib/math').then(function(m) {
  3. alert("2π = " + m.sum(m.pi, m.pi));
  4. });
  5. // Create execution sandboxes – new Loaders
  6. var loader = new Loader({
  7. global: fixup(window) // replace ‘console.log’
  8. });
  9. loader.eval("console.log('hello world!');");
  10. // Directly manipulate module cache
  11. System.get('jquery');
  12. System.set('jquery', Module({$: $})); // WARNING: not yet finalized

Map + Set + WeakMap + WeakSet

对于常用算法来说高效的数据结构,而WeakMaps提供了纺织内存泄露的键值对数据结构,相比来说更安全。

  1. // Sets
  2. var s = new Set();
  3. s.add("hello").add("goodbye").add("hello");
  4. s.size === 2;
  5. s.has("hello") === true;
  6. // Maps
  7. var m = new Map();
  8. m.set("hello", 42);
  9. m.set(s, 34);
  10. m.get(s) == 34;
  11. // Weak Maps
  12. var wm = new WeakMap();
  13. wm.set(s, { extra: 42 });
  14. wm.size === undefined
  15. // Weak Sets
  16. var ws = new WeakSet();
  17. ws.add({ data: 42 });
  18. // 因为添加的对象没有其他的引用,因此其并不会在这个weak set中存储。

Proxies

Proxies 可以为对象增加监听器和处理函数

  1. // 监听普通对象
  2. var target = {};
  3. var handler = {
  4. get: function (receiver, name) {
  5. return `Hello, ${name}!`;
  6. }
  7. };
  8. var p = new Proxy(target, handler);
  9. p.world === 'Hello, world!';
  1. // 监听函数对象
  2. var target = function () { return 'I am the target'; };
  3. var handler = {
  4. apply: function (receiver, ...args) {
  5. return 'I am the proxy';
  6. }
  7. };
  8. var p = new Proxy(target, handler);
  9. p() === 'I am the proxy';

可以监听以下属性:

  1. var handler =
  2. {
  3. get:...,
  4. set:...,
  5. has:...,
  6. deleteProperty:...,
  7. apply:...,
  8. construct:...,
  9. getOwnPropertyDescriptor:...,
  10. defineProperty:...,
  11. getPrototypeOf:...,
  12. setPrototypeOf:...,
  13. enumerate:...,
  14. ownKeys:...,
  15. preventExtensions:...,
  16. isExtensible:...
  17. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注