Published on

ES6标准入门

Authors

ECMAScript 6 Primer


Date: 20180904

第1章 ECMAScript 6 简介

第2章 letconst 命令

2.1 let

  • 类似 var,但是又 locality

  • 代码块内有效

    {
      let a = 10 // 超出此代码块无效, 局部变量
      var b = 5 // 代码块外有效, 作用域: 函数 + 全局
    }
    
  • 变量提升

  • 暂时性死去 temporal dead zone (TDZ)

  • 不允许重复声明

  • block level domain

  • do

    let x = do {
      let t = f()
      t * t + 1
    }
    

2.2 const

定义常量

const PI = 3.1415
const a = []
a.push('Hello')
  • 声明变量的6中方法

    • var

    • function

    • let

    • const

    • import

    • class

顶层对象

  • 浏览器: window

  • Node / web worker: global

  • this

第 3 章 变量的解构赋值 Destructuring assignment

模式匹配

3.1 数组的 Destructuring assignment

let [firstName, surname] = arr
function fibs() {
    let a = 0;
    let b = 1;
    while (true) {
        yield a;
        [a, b] = [b, a + b];
    }
}
let [first, second, third, fourth, fifth, sixth] = fibs();
sixth;

3.2 对象的解构赋值

let jsonData = {
  id: 42,
  status: 'OK',
  data: [867, 5309],
}
let { id, status, data: number } = jsonData

Map

var map = new Map()
map.set('first', 'hello')
map.set('second', 'world')
for (let [key, value] of map) {
  console.log(key + ' is ' + value)
}

TODO:

  • 第 4 章: 字符串的扩展

Q & A

  • javascript 中 ; 使用

    • Stackoverflow: Function expression ending with ; vs. not

      At its root, what you have there is an assignment statement, and according to the Google Javascript Style Guide, all statements should end in a ;. Especially assignment statements. JSLint requires ; or else it won't pass.

  • javascript prototype

    • 动态向 javascript object 添加属性, 每个函数都有一个prototype属性,这个属性是指向一个对象的引用,这个对象称为原型对象,原型对象包含函数实例共享的方法和属性,也就是说将函数用作构造函数调用(使用new操作符调用)的时候,新创建的对象会从原型对象上继承属性和方法。
    function employee(name, job, born) {
      this.name = name
      this.job = job
      this.born = born
    }
    
    var bill = new employee('Bill Gates', 'Engineer', 1985)
    
    employee.prototype.salary = null
    bill.salary = 20000