[关闭]
@bornkiller 2015-03-08T02:54:17.000000Z 字数 3647 阅读 2630

ES6通关之路

javascript


前言

ES6规范年内发布,更多新特性,更多新功能,提前学习使用不可或缺。文中提及代码在iojs-v1.4.3下测试,务必加上"use strict"声明。

变量声明

let var1 [= value1] [, var2 [= value2]] [, ..., varN [= valueN]];

javascript没有块的概念,变量作用域主要以函数作用域[1]形成作用域链。如下示例:

  1. function block() {
  2. for (var i = 0; i < 5; i++) {
  3. console.log(i);
  4. }
  5. console.log(i);
  6. }

for...loop....使用var定义局部变量i,因为作用域是整个函数,所以在循环体外部也是可以访问,在循环内部做的修改都会反映到外部,并不会抛未定义错误。

  1. function block() {
  2. for (let i = 0; i < 5; i++) {
  3. console.log(i);
  4. }
  5. console.log(i);
  6. }

for...loop....使用let定义局部变量i,只在循环体内部可访问,所以循环体外的引用会报错i is not defined

const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]]];

const定义一个常量,且不可被重新赋值。赋值时,会抛出Assignment to constant variable错误。

  1. const title = "love is color blind";
  2. function assignTitle(_title_) {
  3. title = _title_;
  4. }

Collections

新变量类型,阅读相关API文档即可,没有难度。

  1. var object = {}
  2. , array = []
  3. , regexp = new RegExp('\\\/love');
  4. var data = new Map([
  5. ["title", "love is color blind"],
  6. ["content", "reference MDN website for details"]
  7. ]);
  8. data.set(undefined, true);
  9. data.set(null, true);
  10. var weakData = new WeakMap();
  11. weakData.set(object, 'story');
  12. var list = new Set(["title", "content"]);
  13. list.add(null);
  14. list.add(undefined);
  15. var weakList = new WeakSet();
  16. weakList.add(object);
  17. weakList.add(array);

MapObject相似,差异大概有三点:

Promise

javascript异步操作无处不在,将异步操作串行之前是个大麻烦,很容易造成恶魔金字塔。而是用Promise[2],可以有效规避这个问题。

  1. Promise.all(iterable)
  2. Promise.race(iterable)
  3. Promise.reject(reason)
  4. Promise.resolve(value)
  5. Promise.prototype.catch(onRejected)
  6. Promise.prototype.then(onFulfilled, onRejected)

提供了四个静态方法和两个原型方法。简单应用如下:

  1. var title = Promise.resolve("why so serious");
  2. var content = new Promise(function(resolve) {
  3. setTimeout(function() {
  4. resolve("love is color blind");
  5. }, 300);
  6. });
  7. Promise
  8. .race([title, content])
  9. .then(function(value) {
  10. console.log(value);
  11. });
  12. Promise
  13. .all([title, content])
  14. .then(function(value) {
  15. return Promise.reject("explicit reject the next promise");
  16. })
  17. .catch(function(reason) {
  18. console.log(reason);
  19. });
  20. Promise
  21. .all([title, content])
  22. .then(function(value) {
  23. throw new Error("explicit reject the next promise")
  24. })
  25. .catch(function(error) {
  26. console.log(error.message);
  27. });

文档说明很清楚,调用即可。唯一需要注意的是,在then内部的调用函数,如果显式抛出错误,或者return rejected promise,返回的promise状态都未rejected,其他情况下则为resolved

Numeric literal

数值类型支持二进制,八进制,十进制,十六进制数据,示例如下:

  1. let numericArray = [0b1011, 0o11, 12, 0x2F];
  2. numericArray.forEach(function(value) {
  3. console.log(value);
  4. });

输出结果为:11,9,12,47

String Method

新定义字符串操作方法。

  1. String.prototype.startsWith()
  2. String.prototype.endsWith()
  3. String.prototype.includes()
  4. String.prototype.repeat()
  5. String.prototype.normalize()
  1. var title = "love is color blind";
  2. var repeater = "one";
  3. console.log(title.startsWith("love"));
  4. console.log(title.endsWith("blind"));
  5. console.log(title.includes("color"));
  6. console.log(repeater.repeat(3));
  7. console.log(title.normalize());

normalize方法感觉有点诡异,暂时不清楚使用场景。

Template String

Template strings 允许内嵌表达式.
可以分为两种,tag template string, template string。后者使用默认的变量替换行为,如果在变量替换过程中需要进行其他操作,则定义tag function即可。

  1. var title = "love is color blind";
  2. var content = "why so serious";
  3. console.log(`the book talk about ${title}, and mainly content takes ${content}`);
  4. function tagFunction(pieces) {
  5. var result = pieces[0];
  6. var substitutions = Array.prototype.slice.call(arguments, 1);
  7. for (var i = 0; i < substitutions.length; i++) {
  8. result += substitutions[i] + pieces[i+1];
  9. }
  10. return result;
  11. }
  12. console.log(tagFunction `the book talk about ${title}, and mainly content takes ${content}`);

注意两种使用方式的差异。

Class

目前的class实现貌似跟规范相差较远,基本功能已出,如下所示:

  1. "use strict";
  2. class Animal {
  3. constructor(type) {
  4. this.type = type;
  5. }
  6. speak() {
  7. console.log('I belong to animal %s', this.type);
  8. }
  9. }
  10. class Pet extends Animal {
  11. constructor(type, sound, size) {
  12. super(type);
  13. this.sound = sound;
  14. this.size = size;
  15. this.speakTimes = 0;
  16. }
  17. speak() {
  18. this.speakTimes += 1;
  19. super.speak();
  20. }
  21. getSpeakTimes() {
  22. return this.speakTimes;
  23. }
  24. }

[1] 全局作用域与函数作用域
[2] NPM Q模块和现在原生Promise对象
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注