項目中常用的ES6

看代碼及註釋就懂了

把ES6(es2015)代碼轉換爲ES5代碼

  • $ npm install -g babel-cli
  • $ npm install babel-preset-env --save
  • $ babel ./src/es6.js -w --out-file ./dist/es5.js --presets env

解構賦值

const breakfast = () => ['cake', 'coffee', 'apple']
let [dessert, drink, fruit] = breakfast()
console.info(dessert, drink, fruit) // 'cake' 'coffee' 'apple'
const breakfast = () => {
    return {
        dessert: 'cake',
        drink: 'coffee',
        fruit: 'apple'
    }
}
let {dessert, drink, fruit} = breakfast()
console.info(dessert, drink, fruit) // 'cake' 'coffee' 'apple'

字符串

  • 反引號代替引號:`some content ${variable} some content`
  • str.includes()、str.startsWidth()、str.endsWith() 代替了正則表達式匹配

數組展開符

// 利用 Array 的 concat() 實現
let breakfast = ['cake', 'coffee', 'apple']
let food = ['rice', ...breakfast]
console.info(...breakfast, food) // 'cake' 'coffee' 'apple', ["rice", "cake", "coffee", "apple"]

對象

// 對象屬性
let food = {}
let drink = 'hot drink'
food[drink] = 'milk'
console.log(food['hot drink']) // 'milk'
let food = {}
let drink = 'hot drink'
food[drink] = 'milk'

let dessert = 'cake'
food.fruit = 'banane'

let breakfast = Object.assign({}, {dessert}, food) // {dessert} 有屬性有值
console.log(breakfast) // {dessert: "cake", hot drink: "milk", fruit: "banane"}

集合 Set 和 Map

let fruit = new Set(['apple', 'banane', 'orange'])
/* 添加元素,但是不會添加相同的元素,利用這個特性實現數組去重:[...new Set(arr)] */
fruit.add('pear')
/* 元素數量 */
console.log(fruit.size) // 4
/* 是否有指定元素 */
console.log(fruit.has('apple')) // true
/* 刪除元素 */
fruit.delete('banana') 

console.log(fruit) // Set(4) {"apple", "banane", "orange", "pear"}
/* 遍歷 */
fruit.forEach(item => {
    console.log(item)
})
/* 清空 */
fruit.clear()

console.log(fruit) // Set(0) {}
let food = new Map()
let fruit = {}, cook = function(){}, dessert = '甜點'
food.set(fruit, 'apple')
food.set(cook, 'knife')
food.set(dessert, 'cake')

console.log(food, food.size) // Map(3) {{…} => "apple", ƒ => "knife", "甜點" => "cake"} 3

console.log(food.get(fruit)) // "apple"
console.log(food.get(dessert)) // "cake"

food.delete(dessert)
console.log(food.has(dessert)) // false

food.forEach((value, key) => {
    console.log(`${key} = ${value}`) // [object Object] = apple    function(){} = knife
})

food.clear()
console.log(food) // Map(0) {}

Generator

function* calc(num){
    yield num+1
    yield num-2
    yield num*3
    yield num/4
    return num
}
let cal = calc(4)
console.info(
    cal.next(), // {value: 5, done: false}
    cal.next(), // {value: 2, done: false}
    cal.next(), // {value: 12, done: false}
    cal.next(), // {value: 1, done: false}
    cal.next(), // {value: 4, done: true} 遍歷完了後 done:true
    cal.next() // {value: undefined, done: true}
)

class Chef{
    constructor(food){
        this.food = food;
        this.dish = [];
    }
    get menu(){ // 不得有參數(Getter must not have any formal parameters.)
        console.log('getter 取值')
        console.log(this.dish)
        return this.dish
    }
    set menu(dish){ // 必須有一個參數(Setter must have exactly one formal parameter.)
        console.log('setter 存值')
        this.dish.push(dish)
    }
    cook(){
        console.log(this.food)
    }
}
let Gu = new Chef('vegetables');
Gu.cook() // "vegetables"
console.log(Gu.menu) // "get 取值" []

Gu.menu = 'egg' // "setter 存值"
Gu.menu = 'fish' // "setter 存值"

console.log(Gu.menu); // "getter 取值" ["egg", "fish"]
class Person {
    constructor(name, birth){
        this.name = name
        this.birth = birth
    }
    intro(){
        return `${this.name}的生日是${this.birth}`
    }
}

class One extends Person {
    constructor(name, birth){
        super(name, birth)
    }
}

let z = new Person('zz', '01-09')
let x = new One('xx', '01-09')

console.log(z.intro(), x.intro()) // "zz的生日是01-09" "xx的生日是01-09"
// 轉化爲ES5的代碼大概就是
/* function Person(name, birth) {
    this.name = name;
    this.birth = birth;
}
Person.prototype.intro = function () {
    return this.name + '\u7684\u751F\u65E5\u662F' + this.birth;
};
function One(name, birth) {
    Person.apply(this, arguments);
}
One.prototype = new Person();
var z = new Person('zz', '01-09');
var x = new One('xx', '01-09');

console.log(z.intro(), x.intro()); // "zz的生日是01-09" "xx的生日是01-09" */

Promise

  • 回調地獄
function ajax(fn){
    setTimeout(()=>{
        console.log('執行業務')
        fn()
    },1000)
}
ajax(()=>{
    ajax(()=>{
        ajax(()=>{
            ajax(()=>{
                console.log('執行結束4')
            })
            console.log('執行結束3')
        })
        console.log('執行結束2')
    })
    console.log('執行結束1')
})
/*
    效果:
        1s: 執行業務 執行結束1
        2s:  執行業務 執行結束2
        3s: 執行業務 執行結束3
        4s:  執行業務 執行結束4
*/
  • Promise 這樣寫
function delay(word){
    return new Promise((reslove,reject) => {
        setTimeout(()=>{
            console.log('執行業務')
            reslove(word)
        },1000)
    })
}
delay('執行業務1')
    .then(word=>{
        console.log(word)
        return delay('執行業務2')
    })
    .then(word=>{
        console.log(word)
        return delay('執行業務3')
    })
    .then(word=>{
        console.log(word)
        return delay('執行業務4')
    })
    .then(word=>{
        console.log(word)
    })
    .catch()
  • async + await
function delay(word){
    return new Promise((reslove, reject) => {
        setTimeout(()=>{
            console.log('執行業務')
            reslove(word)
        },1000)
    })
}

const start = async () => {
    const word1 = await delay('執行業務1')
    console.log(word1)

    const word2 = await delay('執行業務2')
    console.log(word2)

    const word3 = await delay('執行業務3')
    console.log(word3)
    
    const word4 = await delay('執行業務4')
    console.log(word4)
}

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