大前端學習--ES6 新特性

ES6 新特性

一、ECMAScript 2015

1. ES2015共有三種作用域
  • 全局作用域
  • 函數作用域
  • 塊級作用域(新增)
2. 變量聲明:let const
  • let const都是塊級作用域,let是變量,const是常量
  • for點擊事件
var element = [{}, {}, {}]
for(var i = 0; i < element.length; i++) {
  element[i].onclick = function () {
    // i是全局變量,已經變成了3
    console.log(i)
  }
}
element[2].onclick() // 3

var element = [{}, {}, {}]
for(var i = 0; i < element.length; i++) {
  element[i].onclick = (function (i) {
  // 閉包實現
    return function () {
      console.log(i)
    }
  })(i)
}
element[2].onclick() // 2

var element = [{}, {}, {}]
for(let i = 0; i < element.length; i++) {
  // let定義的變量是塊級作用域
  element[i].onclick = function () {
    console.log(i)
  }
}
element[2].onclick() // 2
  • for生成兩層塊級作用域
for(let i = 0; i < 3; i ++) {
  let i = 'foo'
  console.log(i)
}

let i = 0

if (i < 3) {
  let i = 'foo'
  console.log(i)
}

i++

if (i < 3) {
  let i = 'foo'
  console.log(i)
}

i++

if (i < 3) {
  let i = 'foo'
  console.log(i)
}

i++
  • let const 不會變量提升
console.log(foo) // undefined
var foo = 'jal'

console.log(foo2) // ReferenceError
let foo2 = 'jal'
  • 編碼建議:不用var,主用const,搭配let
3. 數組的解構

方括號[]中的變量按順序匹配數組元素

const arr = [1, 2, 3]
const a = arr[0]
const b = arr[1]
const c = arr[2]
console.log(a, b ,c) // 1 2 3
const [a, b, c] = arr
console.log(a, b ,c) // 1 2 3
const [, , c] = arr
console.log(c) // c
const [a, ...c] = arr // 三個點解構只能用於最後一個位置
console.log(c) // [ 2, 3 ]
const [a] = arr
console.log(a) // 1
const [a, b, c, d] = arr
console.log(d) // undefined
const [a, b, c = 123, d = 'defaultValue'] = arr
console.log(c, d) // 3 defaultValue
const path = 'a/b'
const [, b] = path.split('/')
console.log(b) // b
4. 對象的解構
const obj = {name: 'yibo', age: 22}
const {name} = obj
console.log(name) // yibo
const name = 'jal'
const {name} = obj
console.log(name) // SyntaxError: Identifier 'name' has already been declared
const name = 'jal'
const {name: objName, sex = 'boy'} = obj
console.log(objName, sex) // yibo boy
5. 模板字符串

反引號中間的${}爲JS變量JS表達式

const name = 'yibo'
const str = `this is ${name}`
console.log(str)
6. 模板字符串標籤函數
const str = console.log`hello world` // [ 'hello world' ]

const name = 'tom'
const gender = true
function myTagFunc (str, name, gender) {
  console.log(str, name, gender)  // [ 'hey, ', ' is a ', '.' ] tom true
  return str[0] + name + str[1] + gender + str[2]
}

const result = myTagFunc`hey, ${name} is a ${gender}.`
console.log(result) // hey, tom is a true.
7. 字符串方法
  • .includes()

  • startsWith()

  • endsWith()

const message = 'Error: foo is not undefined.'

console.log(
  message.startsWith('Error'),
  message.endsWith('undefined.'),
	message.includes('foo')
)
// true true true
8. 函數默認值
// 帶有默認值的參數要放在最後
function foo(enable = true) {
  console.log(enable)
}
foo(true) //true
foo(false) //false
foo() // true
9. 剩餘參數

剩餘參數只能出現在形參的最後一位,而且只能使用一次

// function foo(){
//   console.log(arguments)
// }
// foo(1, 2, 3) // [Arguments] { '0': 1, '1': 2, '2': 3 }


// ...args只能出現在形參的最後一位,而且只能使用一次
function foo(...args) {
  console.log(args)
}
foo(1, 2, 3) // [ 1, 2, 3 ]
10. 展開數組
const arr = ['foo', 'bar', 'baz']

console.log.apply(console, arr) // foo bar baz
console.log(...arr) // foo bar baz
11. 箭頭函數
const inc = n => n + 1
console.log(inc(1)) // 2

const sum = (a, b) => {
  return a + b
}
console.log(sum(1, 2)) // 3
  • 箭頭函數不會改變this指向,this爲上層作用域的this
const person = {
  name: 'tom',
  sayHi: function () {
    // this 是 person
    console.log(`hi, my name is ${this.name}`)
  },
  sayHiAync: function () {
    setTimeout(function () {
      //node.js: this 是 {}
      console.log(` sayHiAync: hi, my name is ${this.name}`)
    }, 1000);
  }
}
person.sayHi() // hi, my name is tom
person.sayHiAync() // sayHiAync: hi, my name is undefined
const person = {
  name: 'tom',
  sayHi:  () => {
    // node.js: this是{}
    console.log(`hi, my name is ${this.name}`)
  },
  sayHiAync: function () {
    setTimeout(() => {
      // this是person
      console.log(` sayHiAync: hi, my name is ${this.name}`)
    }, 1000);
  }
}
person.sayHi() // hi, my name is undefined
person.sayHiAync() // sayHiAync: hi, my name is tom
12. 對象字面量增強
  • 屬性名和屬性值相同時可以省略,只寫屬性名
  • 對象方法可以直接寫函數形式:method1(){}
  • 使用方括號的方式計算動態屬性名
const bar = 111
const obj = {
  foo: 123,
  // bar: bar,
  bar, // 同上一行效果
  // method1: function () {
  //   console.log(`method1: ${this}`)
  // },
  method2 () {
    // 直接寫一個方法,同上面的冒號屬性
    console.log(`method2: ${this}`)
  },
  [Math.random()]: 123, // 計算屬性名

}
console.log(obj) // { foo: 123, bar: 111, method2: [Function: method2], '0.13076137144987743': 123 }
13. 對象擴展方法
  • Object.assign(target, source):將多個源對象中的屬性複製到一個目標對象中

    // Object.assign 用第二個參數的對象屬性覆蓋第一個參數的對象。返回結果爲第一個對象
    const source1 = {
      a: 123,
      b: 456
    }
    const source2 = {
      a: 333,
      c: 33
    }
    const target = {
      a: 11,
      b: 22
    }
    
    const result = Object.assign(target, source1, source2)
    console.log(result) // { a: 333, b: 456, c: 33 }
    console.log(result === target) // true
    
    function fun(obj) {
      // obj.name = 'function.obj'
      // console.log(obj)
      const funObj = Object.assign({}, obj)
      funObj.name = 'function.obj'
      console.log(funObj)
    }
    
    const obj = {
      name: 'global obj'
    }
    
    fun(obj)
    console.log(obj)
    
  • Object.is 對===的比較,+0不等於-0, NAN等於NAN

    // Object.is 
    console.log(
      0 === false, // false
      0 == false, // true
      +0 ===-0, // true
      NaN === NaN, // false
      Object.is(+0, -0), // false
      Object.is(NaN, NaN) // true
    )
    
14. 代理對象:Proxy

ES5中有一個Object.defineProperty,Vue2就是通過這個實現數據雙向綁定

ES6提供了Proxy,可以監視對象的讀寫過程,Vue3.0通過Proxy實現數據綁定

// Proxy 
const person = {
  name: 'jal',
  age: 20
}

const personProxy = new Proxy(person, {
  // 參數爲目標對象、屬性名
  get (target, property) {
    return property in target ? target[property]: 'default'
    // console.log(target, property) // { name: 'jal', age: 20 } name
    // return 100
  },
  // 參數爲目標對象、屬性名、屬性值
  set (target, property, value) {
    if(property === 'age') {
      if(!Number.isInteger(value)) {
        throw new TypeError(`${value} is not an int`)
      }
    }
    console.log(target, property, value) // { name: 'jal', age: 20 } gender true
  }
})

personProxy.gender = true
// personProxy.age = '11' // TypeError: 11 is not an int

personProxy.age = 11

// console.log(personProxy.name) // 100
console.log(personProxy.name) // jal
console.log(personProxy.xxx) // default

Proxy對比Object.defineProperty:

  • Object.defineProperty只能監聽屬性的讀寫
  • Proxy能監視更多對象操作:delete
const person = {
  name: 'jal',
  age: 20
}
const personProxy = new Proxy(person, {
  deleteProperty(target, property) {
    console.log('delete', property) // delete age
    delete target[property]
  }
})
delete personProxy.age
  • Proxy更好的支持數組對象的監視(VUE重寫數組的操作方法,劫持方法調用過程)

    const list = []
    const listProxy = new Proxy(list, {
      set(target, property, value) {
        console.log('set', property, value)
        target[property] = value
        return true // 表示設置成功
      }
    })
    listProxy.push(100)
    // set 0 100
    // set length 1
    
15. Reflect 統一的對象操作API

Reflect屬於靜態類(如Math),不能new,只能調用靜態方法:Reflect.get()。Reflect內部封裝了一系列對對象的底層操作。Reflect成員方法就是Proxy處理對象的默認實現

const proxy = new Proxy(obj, {
  get(target, property) {
    // 不寫get邏輯,相當於調用Reflect.get(target, property)。
    return Reflect.get(target, property)
  }
})
  • Reflect統一提供一套用於操作對象的API
const obj = {
  foo: '111',
  bar: 'rrr',
  age: 18
}
// console.log("age" in obj)
// console.log(delete obj['bar'])
// console.log(Object.keys(obj))

console.log(Reflect.has(obj, 'name')) // false
console.log(Reflect.deleteProperty(obj, 'bar')) // true
console.log(Reflect.ownKeys(obj)) // [ 'foo', 'age' ]
16. Promise

一種更優的異步編程解決方案。解決了傳統異步編程中回調函數嵌套過深的問題

17. 類 關鍵詞 Class
// function Person(name) {
//   this.name = name
// }
// Person.prototype.say = function() {
//   console.log(`hi, my name is ${this.name}`)
// }
// const p = new Person('jal')
// p.say() // hi, my name is jal

class Person {
  constructor(name) {
    this.name = name
  }
  say () {
  console.log(`hi, my name is ${this.name}`)
  }
}
const p = new Person('jal')
p.say() // hi, my name is jal
  • 靜態方法, this 指向當前類型,而不是實例

    class Person {
      constructor(name) {
        this.name = name
      }
      say () {
      console.log(`hi, my name is ${this.name}`)
      }
      static create(name) {
        // this 指向當前類型,而不是實例
        console.log(this) // [Function: Person]
        return new Person(name)
      }
    }
    
    const tom = Person.create('tom')
    tom.say() // hi, my name is tom
    
  • 繼承,關鍵詞 extends

    class Student extends Person {
      constructor(name, number){
        super(name)
        this.number = number
      }
    
      hello () {
        super.say()
        console.log(`my school number is ${this.number}`)
      }
    }
    
    const s = new Student('jack', 100)
    s.hello()
    // hi, my name is jack
    // my school number is 100
    
18. 數據結構 Set
// Set 數據結構
const s = new Set()
s.add(1).add(2).add(3).add(4).add(2)
console.log(s) // Set(4) { 1, 2, 3, 4 }

s.forEach(i => console.log(i)) // 1 2 3 4

for(let i of s) {
  console.log(i)
}
// 1 2 3 4

console.log(s.size) // 4

console.log(s.delete(3)) // true
console.log(s) // Set(3) { 1, 2, 4 }

const arr = [1, 2, 1, 3, 4 ,1]
const result = new Set(arr)
console.log(result) // Set(4) { 1, 2, 3, 4 }
const arr2 = Array.from(result)
console.log(arr2) // [ 1, 2, 3, 4 ]
const arr3 = [...result]
console.log(arr3) // [ 1, 2, 3, 4 ]
19. 數據結構 Map

Map 映射任意類型之間的關係. Map可以用任意對象作爲鍵,而對象只能用字符串作爲鍵

// Map 映射任意類型之間的關係. Map可以用任意對象作爲鍵,而對象只能用字符串作爲鍵
const obj = {}
obj[true] = 'value'
obj[1] = '11'
obj[{a: 1}] = '33'
console.log(Object.keys(obj)) // [ '1', 'true', '[object Object]' ]

const m = new Map()
const tom = {name: 'tom'}
m.set(tom, 90)
console.log(m) // Map(1) { { name: 'tom' } => 90 }
console.log(m.get(tom)) // 90
20. 原始數據類型 Symbol

最主要的作用就是爲對象添加獨一無二的屬性名

const s = Symbol()
console.log(s) // Symbol()
console.log(typeof s) // symbol

console.log(Symbol() === Symbol()) // false

console.log(Symbol('foo')) // Symbol(foo)
console.log(Symbol('bar')) // Symbol(bar)
console.log(Symbol('baz')) // Symbol(baz)

const obj = {}
obj[Symbol()] = 111
obj[Symbol()] = 2
console.log(obj) // { [Symbol()]: 111, [Symbol()]: 2 }


const name = Symbol()
const person = {
  [name]: 'jal', // 作爲私有成員防止被訪問
  say(){
    console.log(this[name])
  }
}
person.say()// jal
console.log(person[Symbol()]) // undefined
// console.log(person[name]) // jal

截止到ES2019一共定義了6種原始類型,和一個object類型,未來還會增加一個bigint的原始類型(stage-4階段)標準化過後就是8種數據類型了

boolean symbol number string undefined null object bigint

const s1 = Symbol.for('foo')
const s2 = Symbol.for('foo')
console.log(
  s1 === s2, // true
// Symbol.for的參數會被轉化爲字符串
Symbol.for(true) === Symbol.for('true'), // true
)
const obj2 = {
  // 爲對象實現迭代器時會用到
  [Symbol.toStringTag]: 'XObject'
}
console.log(obj2.toString()) // [object Object] [object XObject]

const obj3 = {
  [Symbol()]: 'symbol value',
  foo: 'normal value'
}
for(var key in obj3) {
  console.log(key)
}
// foo

console.log(Object.keys(obj3)) // [ 'foo' ]
console.log(JSON.stringify(obj3)) // {"foo":"normal value"}

console.log(Object.getOwnPropertySymbols(obj3)) // [ Symbol() ]
21. for … of 作爲遍歷所有數據結構的統一方式
// for ... of 循環, 可以使用break
const arr = [1, 2, 3, 4]
for (const item of arr) { // item爲每個對象實例
  console.log(item)
}
// 相當於
// arr.forEach(item => {
//   console.log(item)
// })

可以使用break終止循環

// arr.forEach ,但是這個方法不能終止遍歷
// 爲了終止遍歷,我們之前,我們曾使用
// arr.some() 返回true
// arr.every() 返回false

for(const item of arr) {
  console.log(item) 
  if(item > 1)break
}

遍歷集合Set

const s = new Set(['foo', 'bar'])
for(const item of s) {
  console.log(item)
}
// foo bar

遍歷集合Map

const m = new Map()
m.set('foo', '123')
m.set('bar', '34')

for(const item of m) {
  console.log(item)
}
// [ 'foo', '123' ]  [ 'bar', '34' ]

// 解構鍵和值
for(const [key, value] of m) {
  console.log(key,value)
}
// foo 123
// bar 34

遍歷對象,報錯了:TypeError: obj is not iterable

const obj = {name: 'jal', age: 22}

for(const item of obj) {
  console.log(item) // TypeError: obj is not iterable
}

ES中能夠表示有結構的數據類型越來越多

22. Iterable接口(可迭代接口)

實現Iterable結構就是for…of的前提

  • 實現可迭代接口
// 迭代器 iterator 
const set = new Set(['foo', 'bar', 'baz'])

const iterator = set[Symbol.iterator]()

// 這就是for... of 循環實現的工作原理
console.log(iterator.next())
console.log(iterator.next())
console.log(iterator.next())
console.log(iterator.next())
// { value: 'foo', done: false }
// { value: 'bar', done: false }
// { value: 'baz', done: false }
// { value: undefined, done: true }
  • 實現迭代器原理:
// obj 實現可迭代接口 Iterable
const obj = {
  // iterator 方法
  [Symbol.iterator]: function () {
    // 迭代器接口 iterator 
    return {
      // 必須要有next方法
      next: function () {
        // 迭代結果接口 IterationResult
        return {
          value: 1,
          done: true
        }
      }
    }
  }
}
  • 具體實現:
const obj = {
  store: ['foo', 'bar', 'baz'],

  [Symbol.iterator]: function () {
    let index = 0
    const self = this

    return {
      next: function () {
        const result = {
          value: self.store[index],
          done: index >= self.store.length
        }
        index++
        return result
      }
    }
  }
}

for( const item of obj) {
  console.log(item)
}
// foo
// bar
// baz

上面就是設計模式中的迭代器模式。

小案例:

const todos = {
  life: ['吃飯', '睡覺', '打豆豆'],
  learn: ['語文', '數學', '英語'],
  work: ['喝茶'],
  each: function (callback) {
    const all = [].concat(this.life, this.learn, this.work)
    for (const item of all) {
      callback (item)
    }
  },
  // 實現迭代器接口
  [Symbol.iterator]: function () {
    const all = [...this.life, ...this.learn, ...this.work]
    let index = 0
    return {
      next: function () {
        return {
          value: all[index],
          done: index++ >= all.length
        }
      }
    }
  }
}

todos.each(function (item) {
  console.log(item)
})
console.log('---------')
for(const item of todos) {
  console.log(item)
}
// 吃飯
// 睡覺
// 打豆豆
// 語文
// 數學
// 英語
// 喝茶
// ---------
// 吃飯
// 睡覺
// 打豆豆
// 語文
// 數學
// 英語
// 喝茶
22. 生成器函數 generator

避免異步編程中回調函數嵌套過深,提供更好的異步編程解決方案

function * foo () {
  console.log('zce')
  return 100
}
// 這個foo就是一個Generator函數

const result = foo()
console.log(result)// Object [Generator] {}
console.log(result.next())
// zce
// { value: 100, done: true }
// 可以看出生成器對象實現了Iterator接口

配合yield關鍵詞使用。

生成器函數會返回一個生成器對象,調用這個生成器對象的next方法,纔會讓函數體執行,一旦遇到了yield關鍵詞,函數的執行則會暫停下來,next函數的參數作爲yield結果返回,如果繼續調用函數的next函數,則會再上一次暫停的位置繼續執行,直到函數體執行完畢,next返回的對象的done就變成了true

function * fn () {
  console.log(111)
  yield 100
  console.log(222)
  yield 200
  console.log(333)
  yield  300
}

const generator = fn()

console.log(generator.next())
// 111
// { value: 100, done: false }
console.log(generator.next())
// 222
// { value: 200, done: false }
console.log(generator.next())
// 333
// { value: 300, done: false }

案例1:發號器:

// Generator 應用: 發號器

function * createIdMaker () {
  let id = 1
  while(true) {
    yield id++
  }
}
const idMaker = createIdMaker()

console.log(idMaker.next())
console.log(idMaker.next())
console.log(idMaker.next())
console.log(idMaker.next())
console.log(idMaker.next())
// { value: 1, done: false }
// { value: 2, done: false }
// { value: 3, done: false }
// { value: 4, done: false }
// { value: 5, done: false }

案例2:

Generator函數實現迭代器Iterator
const todos = {
  life: ['吃飯', '睡覺', '打豆豆'],
  learn: ['語文', '數學', '英語'],
  work: ['喝茶'],

  // 實現迭代器接口
  [Symbol.iterator]: function * () {
    const all = [...this.life, ...this.learn, ...this.work]
    for (const item of all) {
      yield item
    }
  }
}

for(const item of todos) {
  console.log(item)
}
// 吃飯
// 睡覺
// 打豆豆
// 語文
// 數學
// 英語
// 喝茶
23. ES Modules

語言層面的模塊化標準


二、ECMAScript 2016

1. 數組的includes方法
const arr = ['foo', 1, false, NaN]
// 以前使用indexOf, 存在則返回下標,不存在則返回-1, 缺點是無法判斷NaN
console.log(arr.indexOf('foo')) // 0
console.log(arr.indexOf(1)) // 1
console.log(arr.indexOf(false)) // 2
console.log(arr.indexOf(NaN)) // -1

console.log(arr.includes('foo')) // true
console.log(arr.includes(1)) // true
console.log(arr.includes(false)) // true
console.log(arr.includes(NaN)) // true
2. 指數運算符:**
console.log(2 ** -52) // 2.220446049250313e-16

三、ECMAScript 2017

1. Object.values(obj)

獲取對象所有的值數組

const obj = {
  name: 'jal',
  age: 20
}
// 對象的值組成的數組
console.log(Object.values(obj)) // [ 'jal', 20 ]
2. Object.entries(obj)

獲取對象的鍵值數組

// 對象的鍵值數組, 可以for...of 這個對象了
console.log(Object.entries(obj)) // [ [ 'name', 'jal' ], [ 'age', 20 ] ]
for (const [key, value] of Object.entries(obj)) {
  console.log(key, value)
}
// name jal
// age 20

console.log(new Map(Object.entries(obj))) // Map(2) { 'name' => 'jal', 'age' => 20 }
3. Object.getOwnPropertyDescriptors(obj)

獲取對象的詳細描述

const p1 = {
  firstName: 'Ji',
  lastName: 'Ailing',
  get fullName() {
    return this.firstName + ' '+ this.lastName
  }
}

const p2 = Object.assign({}, p1)
p2.firstName = 'zce'
console.log(p2) // { firstName: 'zce', lastName: 'Ailing', fullName: 'Ji Ailing' }
const descriptors = Object.getOwnPropertyDescriptors(p1)
console.log(descriptors)
/*
{
  firstName: { value: 'Ji', writable: true, enumerable: true, configurable: true },
  lastName: {
    value: 'Ailing',
    writable: true,
    enumerable: true,
    configurable: true
  },
  fullName: {
    get: [Function: get fullName],
    set: undefined,
    enumerable: true,
    configurable: true
  }
}
*/

const p3 = Object.defineProperties({}, descriptors)
p3.firstName = 'zce'
console.log(p3.fullName) // zce Ailing
4. padEnd/padStart

用指定字符串填充目標字符串的頭部或者尾部,直到達到指定的長度爲止

const books = {
  html: 5,
  css: 16,
  javascript: 128
}
for(const [key, value] of Object.entries(books)) {
  console.log(key, value)
}
// html 5
// css 16
// javascript 128

for(const [key, value] of Object.entries(books)) {
  console.log(`${key.padEnd(16, '-')}|${value.toString().padStart(3, '0')}`)
}
// html------------|005
// css-------------|016
// javascript------|128
5. 在函數參數中添加尾逗號
function foo (
 bar, 
 baz,
) {
  
}

const arr = [
  10,
  20,
  30,
]
6. Async / Await

Promise的語法糖,解決了回調地獄的問題。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章