美文网首页
超详细 ES6 代码段

超详细 ES6 代码段

作者: 阿昕_ | 来源:发表于2018-08-13 18:07 被阅读217次

    let和const

    /* 
        1. let和const
    */
    
    (() => {
        // let: 块级作用域
        for (let i = 0; i < 3; i++) {
            console.log(i) // 0 1 2
        }
        console.log(i) // Uncaught ReferenceError: i is not defined
    })()
    
    (() => {
        // const: 常量 块级作用域
        const t2 = { a: 1}
        t2.a = 3
        console.log(t2.a) // 3    **引用类型 存放的是地址 
        const t1 = 1
        t1 = 2
        console.log(t1) // Uncaught TypeError: Assignment to constant variable.
    })()
    

    解构赋值

    /* 
        2. 解构赋值
    */
    
    // 数组
    {
        let [a, b] = [1, 2]
        console.log(a, b) // 1 2
    }
    {
        let [a, b, ...res] = [1, 2, 3, 4, 5]
        console.log(a, b, res) // 1 2 [3, 4, 5]
    }
    {
        let [a, b, c = 3] = [1, 2]
        console.log(a, b, c) // 1 2 3
    }
    {
        let [a, b, c] = [1, 2]
        console.log(a, b, c) // 1 2 undefined
    }
    {
        let [a, b, c = 3] = [1, 2, 4]
        console.log(a, b, c) // 1 2 4
    }
    {
        let [a,,,b] = [1, 2, 3, 4]
        console.log(a, b) // 1 4
    }
    {
        let a = 1, b = 2;
        [a, b] = [b, a]
        console.log(a, b) // 2 1
    }
    {
        let [a, b] = (() => [1, 2])()
        console.log(a, b) // 1 2
    }
    
    // 对象
    {
        let {a, b} = { a: 1, b: 2}
        console.log(a, b) // 1 2
    }
    {
        let {a = 10, b = 20} = {a: 1}
        console.log(a, b) // 1 20
    }
    {
        let {name:myName, num:[{a, b}]} = {
            name: 'lx',
            num: [{ a: 1, b: 2}]
        }
        console.log(myName, a, b) // lx 1 2
    }
    

    正则

    /* 
        3. 正则
    */
    {
        // es5
        let reg1 = new RegExp('abc', 'i')
        let reg2 = new RegExp(/abc/i)
        console.log(reg1, reg2) //       /abc/i     /abc/i
        console.log(reg1.test('abc123')) // true
        // es6
        let reg3 = new RegExp(/abc/i, 'g')
        console.log(reg3.flags) // g
    }
    {
        // y 修饰符的作用与 g 修饰符类似,也是全局匹配,后一次匹配都从上一次匹配成功的下一个位置开始。
        // 不同之处在于,g 修饰符只要剩余位置中存在匹配就可,而 y 修饰符确保匹配必须从剩余的第一个位置开始,这也就是“粘连”的含义
        let str = 'a1_aa2_aaa3_aaaa4'
        let reg1 = /a+/g
        let reg2 = /a+/y
        console.log(reg1.sticky, reg2.sticky) // false true
        console.log(reg1.exec(str)) // ["a", index: 0, input: "a1_aa2_aaa3_aaaa4"]
        console.log(reg2.exec(str)) // ["a", index: 0, input: "a1_aa2_aaa3_aaaa4"]
    
        console.log(reg1.exec(str)) // ["aa", index: 3, input: "a1_aa2_aaa3_aaaa4"]
        console.log(reg2.exec(str)) // null
    
        console.log(reg1.exec(str)) // ["aaa", index: 7, input: "a1_aa2_aaa3_aaaa4"]
        console.log(reg2.exec(str)) // ["a", index: 0, input: "a1_aa2_aaa3_aaaa4"]
    }
    {
        console.log(/^\uD83D/.test('\uD83D\uDC2A')) // true
        console.log(/^\uD83D/u.test('\uD83D\uDC2A')) // false
        console.log(/\u{61}/.test('a')) // false
        console.log(/\u{61}/u.test('a')) // true
    }
    

    字符串

    /* 
        4. 字符串
    */
    {
        let str = 'abc123'
        console.log(str.includes(3)) // true
        console.log(str.startsWith('a')) // true
        console.log(str.endsWith('3')) // true
    }
    {
        let str = 'liuxin'
        console.log(str.repeat(3)) // liuxinliuxinliuxin
    }
    {
        let str = 'liuxin'
        console.log(`my name is ${str}`) // my name is liuxin
    }
    
    {
        console.log('1'.padStart(5, '0')) // 00001
        console.log('1'.padEnd(5, '*')) // 1****
    }
    
    {
        function test(a, b, c) {
            console.log(a, b, c) // ["my name is ", ", i am ", " years old."]   "liuxin"  20
        }
        let obj = {
            name: 'liuxin',
            age: 20
        }
        test`my name is ${obj.name}, i am ${obj.age} years old.`
    }
    
    {
        console.log(String.raw`liu\nxin${1+1}`) // liu\nxin2
        console.log(`liu\nxin${1+1}`)
    }
    
    {
        console.log(`\u0061`) // a
        console.log(`\u20bb7`) // ₻7
        console.log(`\u{20bb7}`) // 𠮷   大于两个字节
    }
    
    {
        let str = '𠮷a'
        console.log(str.length) // 3
        console.log(str.charAt(0), str.charAt(1), str.charAt(2)) // � � a
        console.log(str.charCodeAt(0), str.charCodeAt(1), str.charCodeAt(2)) // 55362 57271 97
        console.log(str.codePointAt(0).toString(16), str.codePointAt(1).toString(16), str.codePointAt(2).toString(16)) // 20bb7 dfb7 61   **es6
    
        console.log(String.fromCharCode('0x20bb7')) // ஷ
        console.log(String.fromCodePoint('0x20bb7')) // 𠮷   **es6
    
        for (let i = 0; i < str.length; i++) {
            console.log(str[i]) // � � a
        }
        
        for (let i of str) {
            console.log(i) // 𠮷 a
        }
    }
    

    数值

    /* 
        5. 数值
    */
    {
        console.log(0b011001) // 25  ** 0b二进制
        console.log(0o734) // 476  ** 0o八进制
        console.log(Number.isFinite(15)) // true
        console.log(Number.isFinite(NaN)) // false
        console.log(Number.isFinite(1/0)) // false  ** 1/0 ===> Infinity
    
        console.log(Number.isNaN(7)) // false
        console.log(Number.isNaN(NaN)) // true
    
        console.log(Number.isInteger(2)) // true
        console.log(Number.isInteger(2.0)) // true
        console.log(Number.isInteger(2.9)) // false
    
        console.log(Number.MAX_SAFE_INTEGER) // 9007199254740991
        console.log(Number.MIN_SAFE_INTEGER) // -9007199254740991
    
        console.log(Number.isSafeInteger(13), Number.isSafeInteger(9007199254740999)) // true false
    
        console.log(Math.trunc(1.2)) // 1
        console.log(Math.trunc(1.8)) // 1
    
        console.log(Math.sign(-10)) // -1
        console.log(Math.sign(0)) // 0
        console.log(Math.sign(10)) // 1
        console.log(Math.sign('ddd')) // NaN
        console.log(Math.sign('-10')) // -1
    
        console.log(Math.cbrt(8)) // 2      **立方根
        console.log(3**2) // 9      **乘方
    }
    
    

    数组

    /* 
        6. 数组
    */
    {
        let arr1 = Array.of(1, 2, 3, 4)
        let arr2 = Array.of()
        console.log(arr1, arr2) // [1, 2, 3, 4]     []
    }
    
    {
        let p = document.querySelectorAll('p')
        console.log(Array.isArray(p)) // false
        p = Array.from(p)
        console.log(Array.isArray(p)) // true
        p.forEach((item) => {
            console.log(item.textContent)
        })
    
        console.log(Array.from([1, 2, 3], (item) => {return item * 2})) // [2, 4, 6]
    }
    
    {
        console.log([1, 3, 5, undefined, null].fill(999)) // [999, 999, 999, 999, 999]
        console.log([1, 3, 5, undefined, null].fill(999, 2, 4)) // [1, 3, 999, 999, null]   ** 下标从0开始 替换[2,4)的值为999
    }
    
    {
        for (let i of [1, 2, 3, 4].keys()) {
            console.log(i) // 0 1 2 3
        }
        for (let v of [1, 2, 3, 4].values()) {
            console.log(v) // 1 2 3 4
        }
        for (let [i, v] of [1, 2, 3, 4].entries()) {
            console.log(i, v) // 0 1         1 2         2 3             3 4
        }
    }
    {
        console.log([1, 2, 3, 4, 5, 6, 7].copyWithin(3, 0, 2)) // [1, 2, 3, 1, 2, 6, 7]
    }
    

    函数

    /* 
        7. 函数
    */
    
    {
        (function(x, y = 2){
            console.log(x, y) // 1 2
        })(1)
    }
    
    {
        let x = 'test';
        (function(x, y = x){
            console.log(x, y) // hello hello
        })('hello');
    
        (function(x, y = x){
            console.log(x, y) // undefined undefined
        })();
    
        (function(z, y = x){
            console.log(z, y) // 111 test
        })('111')
    }
    
    {
        (function(...res){
            console.log(res) // [1, 2, 3, 4]
        })(1, 2, 3, 4)
    
        console.log(...[1, 2, 3, 4]) // 1 2 3 4
    }
    
    {
        let arr = v => v * 3
        console.log(arr(4)) // 12
    }
    
    {
        function a(x) {
            console.log(x)
        }
    
        function b(x) {
            return a(x)
        }
    
        b(1) // 1
    }
    
    {
        'use strict';
        function fab(n, total = 1) {
            if (n === 1) {return total}
            return fab(n - 1, n * total)
        }
        console.log(fab(5)) // 120
    }
    

    对象

    /* 
        8. 对象
    */
    
    {
        let a = 1
        let b = 2
        let obj = {
            a,
            b
        }
        console.log(obj) // {a: 1, b: 2}
    }
    
    {
        let obj5 = {
            fn: function(){
                console.log('es5')
            }
        }
    
        let obj6 = {
            fn(){
                console.log('es6')
            }
        }
        obj5.fn() // es5
        obj6.fn() // es6
    }
    
    {
        let a = 'num'
        let obj5 = {
            a: 1
        }
        let obj6 = {
            [a]: 1
        }
        console.log(obj5, obj6) // {a: 1}   {num: 1}
    }
    
    {
        console.log(Object.is(4, 4), 4 === 4) // true true
        console.log(Object.is([], []), [] === []) // false false
        console.log(Object.is(NaN, NaN), NaN === NaN) // true false
        console.log(Object.is(0, -0), 0 === -0) // false true
    }
    
    {
        console.log(Object.assign({a: 1}, {b: 2})) // {a: 1, b: 2}      **浅拷贝
    }
    
    {
        for (let [k, v] of Object.entries({a: 1, b: 2})) {
            console.log(k, v) // a 1            b 2
        }
    }
    
    

    Symbol

    /* 
        9. Symbol
    */
    {
        let a = Symbol()
        let b = Symbol()
        console.log(a, b, a === b) // Symbol() Symbol() false
    
        let c = Symbol.for('e')
        let d = Symbol.for('e')
        console.log(c, d, c === d) // Symbol(e) Symbol(e) true
    }
    
    {
        let a = Symbol('a')
        let obj = {
            [a]: '123',
            a: 1
        }
        console.log(obj) // {a: 1, Symbol(a): "123"}
    
        console.log( Object.entries(obj) ) // [ ["a", 1] ]
    
        console.log( Object.getOwnPropertySymbols(obj) ) // [Symbol(a)]
    
        console.log( Reflect.ownKeys(obj) ) // ["a", Symbol(a)]
    }
    

    Set

    /* 
        10. Set
    */
    {
        let list = new Set()
        list.add(1)
        list.add(2)
        list.add(2)
        list.add(2)
        list.add(3)
        console.log(list, list.size) // Set(3) {1, 2, 3}  3
    }
    
    {
        let arr = [1, 2, 3, 4, 5]
        let list = new Set(arr)
        console.log(list, list.size) // Set(5) {1, 2, 3, 4, 5}  5
    }
    
    {
        let arr = [1, 2, 3]
        let list = new Set(arr)
        console.log(list.add(4), list) // Set(4) {1, 2, 3, 4}       Set(4) {1, 2, 3, 4}
        console.log(list.delete(4), list) // true    Set(3) {1, 2, 3}
        console.log(list.has(1)) // true
        console.log(list.clear(), list) // undefined     Set(0) {}
    }
    
    {
        let arr = [1, 2]
        let list = new Set(arr)
        for(let [key, value] of list.entries()) {
            console.log(key, value) // 1 1          2 2
        }
    }
    
    {
        let obj = {a: 1}
        let weakList = new WeakSet()
        console.log(weakList.add(obj))
        console.log(weakList.add(1)) // Invalid value used in weak set
    }
    

    Map

    /* 
        11. Map
    */
    {
        let map = new Map()
        let arr = [1, 2, 3]
        map.set(arr, 456)
        console.log(map, map.get(arr)) // Map(1) {Array(3) => 456}      456
    }
    
    {
        let map = new Map([['name', 'lx'], ['age', 21]])
        console.log(map, map.size) // Map(2) {"name" => "lx", "age" => 21}      2
        console.log(map.delete('age'), map) // true         Map(1) {"name" => "lx"}
        console.log(map.clear(), map) // undefined      Map(0) {}
    }
    
    {
        let obj = {a: 1}
        let weakList = new WeakMap()
        console.log(weakList.set(obj, 1))
        console.log(weakList.set('age', 1)) // Invalid value used as weak map key
    }
    

    Map / Array / Set /Object

    /* 
        12. Map / Array / Set /Object
    */
    
    {
        let map = new Map()
        let array = []
    
        map.set('name', 'lx')
        array.push({name: 'lx'})
        console.log('增', map, array) // Map(1) {"name" => "lx"}         [{name: "lx"}]
    
        console.log('查', map.has('name'), array.find(item => item.name)) // true        {name: "lx"}
    
        map.set('name', 'liuxin')
        array.forEach(item => item.name ? item.name='liuxin' : '')
        console.log('改', map, array) // Map(1) {"name" => "liuxin"}      [{name: "liuxin"}]
    
        map.delete('name')
        array.splice(array.findIndex(item => item.name), 1)
        console.log('删', map, array) // Map(0) {}       []
    }
    
    {
        let set = new Set()
        let array = []
    
        set.add({name:'lx'})
        array.push({name: 'lx'})
        console.info('增', set, array) // Set(1) {{"name" => "lx"}}  [{name: "lx"}] 
    
        console.info('查', set.has({name:'lx'}), array.find(item => item.name)) // false         {name: "lx"}
    
        set.forEach(item => item.name ? item.name='liuxin' : '')
        array.forEach(item => item.name ? item.name='liuxin' : '')
        console.info('改', set, array) // Set(1) {{"name" => "liuxin"}}       [{name: "liuxin"}]
    
        set.forEach(item => item.name ? set.delete(item) : '')
        array.splice(array.findIndex(item => item.name), 1)
        console.info('删', set, array) // Set(0) {}      []
    }
    
    {
        let test = {name:'lx'}
        let map = new Map()
        let set = new Set()
        let obj = {}
    
        map.set('name', 'lx')
        set.add(test)
        obj['name'] = 'lx'
        console.info('增', map, set, obj) // Map(1) {"name" => "lx"}     Set(1) {{…}}    {name: "lx"}
    
        console.log('查', map.has('name'), set.has(test), 'name' in obj) // true true true
    
        map.set('name', 'liuxin')
        test.name = 'liuxin'
        obj['name'] = 'liuxin'
        console.log('改', map, set, obj) // Map(1) {"name" => "liuxin"} Set(1) {{…}} {name: "liuxin"}
    
        map.delete('name')
        set.delete(test)
        delete obj['name']
        console.log('删', map, set, obj) // Map(0) {}            Set(0) {}               {}
    }
    

    Proxy / Reflect

    /* 
        13. Proxy    Reflect 
    */
    {
        // 原始对象
        let obj = {
            name: 'lx',
            age: 20,
            grade: 50
        }
    
        // 生成代理对象
        let monitor = new Proxy(obj, {
            get(target, key) {
                return target[key].replace('l','L')
            },
            set(target, key, value){
                if(key === 'age') {
                    return target[key] = value + '岁'
                } else {
                    return target[key]
                }
            },
            has(target, key) {
                if(key === 'age'){
                    return target[key]
                } else {
                    return false
                }
            },
            deleteProperty(target, key) {
                if(key === 'age'){
                    delete target[key]
                    return true
                } else {
                    return target[key]
                }
            },
            ownKeys(target) {
                return Object.keys(target).filter(item => item != 'name')
            }
        })
    
        monitor.age = 30
        console.log(monitor.name, monitor) // Lx
        console.log(monitor.name, monitor) // Lx
    
        delete monitor.age
        delete monitor.name
        console.log(monitor)
    
        console.log(Object.keys(monitor))
    }
    
    {
        let obj = {
            name: 'lx',
            age: 20,
            grade: 50
        }
        console.log(Reflect.get(obj, 'name'))       // lx
    
        Reflect.set(obj, 'name', 'liuxin')
        console.log(obj)    // {name: "liuxin", age: 20, grade: 50}
    
        console.log(Reflect.has(obj, 'name'))   // true
    }
    
    {
        function validator(target, validator) {
            return new Proxy(target, {
                _validator: validator,
                set(target, key, value, proxy) {
                    if (target.hasOwnProperty(key)) {
                        let v = this._validator[key]
                        if (!!v(value)) {
                            return Reflect.set(target, key, value, proxy)
                        } else {
                            throw Error(`不能设置${key}到${value}`)
                        }
                    } else {
                        throw Error(`${key}不存在`)
                    }
                }
            })
        }
    
        const personValidators = {
            name(val){
                return typeof val === 'string'
            },
            age(val){
                return typeof val === 'number' && val > 18
            }
        }
    
        class Person{
            constructor(name, age){
                this.name = name
                this.age = age
                return validator(this, personValidators)
            }
        }
    
        const person = new Person('liuxin', 20)
    
        console.log(person)
    
        person.name = 'lx'
    }
    

    /* 
        14. 类
    */
    {
        class Parent{
            constructor(name = 'liuixn'){
                this.name = name
            }
        }
        let p1 = new Parent()
        console.log(p1)     // Parent {name: "liuixn"}
    }
    
    {
        class Parent{
            constructor(name = 'liuixn'){
                this.name = name
            }
        }
        class Child extends Parent{ // 继承父类
            constructor(name = 'child'){
                super(name) // 执行父类构造函数
                this.type = 'child'
            }
        }
    
        let c1 = new Child()
        console.log(c1) // Child {name: "child", type: "child"}
    }
    
    {
        class Parent{
            constructor(name = 'liuixn'){
                this.name = name
            }
    
            get info(){
                return this.name + '18岁'
            }
    
            set info(v){
                this.name = v
            }
        }
    
        let p1 = new Parent()
        console.log(p1.info) // liuixn18岁
        p1.info = 'lx'
        console.log(p1.info) // lx18岁
    }
    
    {
        class Parent{
            constructor(name = 'liuixn'){
                this.name = name
            }
    
            static say(){ // 静态方法
                console.log('hello')
            }
        }
        Parent.type = 'type' // 静态属性
    
        console.log(Parent.type) // type
    
        Parent.say() // hello
    }
    

    Promise

    /* 
        15. Promise
    */
    {
        // es5
        let ajax = function(cb){
            console.log('执行')
            setTimeout(function() {
                cb && cb.call()
            }, 1000)
        }
        ajax(function(){
            console.log('我是cb')
        })
    }
    
    {
        // es6
        let ajax = function(){
            console.log('执行')
            return new Promise(function(resolve, reject){
                setTimeout(function() {
                    resolve()
                }, 1000)
            })
        }
        ajax().then(function(){
            console.log('我是promise then')
        })
    }
    
    {
        function loadImg(src) {
            return new Promise((resolve, reject) => {
                let img = document.createElement('img')
                img.src = src
                img.onload = function() {
                    resolve(img)
                }
                img.onerror = function(err) {
                    reject(err)
                }
            })
        }
    
        function showImgs(imgs) {
            imgs.forEach(item => {
                document.body.appendChild(item)
            })
        }
    
        Promise.all([
            loadImg('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534399673304&di=34c8492e2db9d9396cc21be64f786e0e&imgtype=0&src=http%3A%2F%2Fa.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F0824ab18972bd4077557733177899e510eb3096d.jpg'),
            loadImg('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534399707919&di=b290a002e96a76513a3245751302c102&imgtype=0&src=http%3A%2F%2Fg.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F8601a18b87d6277fb82be3f124381f30e924fc3a.jpg'),
            loadImg('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534399721104&di=b61744250c3a8fe6e332d80540de49fb&imgtype=0&src=http%3A%2F%2Fe.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F0d338744ebf81a4cf5534502db2a6059242da69c.jpg'),
            loadImg('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534399739560&di=4535fb90acd623c3e92cb694a00f115b&imgtype=0&src=http%3A%2F%2Fe.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2Ff9198618367adab4bee9208d87d4b31c8601e4c7.jpg')
        ]).then(showImgs)
    }
    
    {
        function loadImg(src) {
            return new Promise((resolve, reject) => {
                let img = document.createElement('img')
                img.src = src
                img.onload = function() {
                    resolve(img)
                }
                img.onerror = function(err) {
                    reject(err)
                }
            })
        }
    
        function showImg(img) {
            document.body.appendChild(img)
        }
    
        Promise.race([
            loadImg('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534399721104&di=b61744250c3a8fe6e332d80540de49fb&imgtype=0&src=http%3A%2F%2Fe.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F0d338744ebf81a4cf5534502db2a6059242da69c.jpg'),
            loadImg('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534399707919&di=b290a002e96a76513a3245751302c102&imgtype=0&src=http%3A%2F%2Fg.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F8601a18b87d6277fb82be3f124381f30e924fc3a.jpg'),
            loadImg('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534399673304&di=34c8492e2db9d9396cc21be64f786e0e&imgtype=0&src=http%3A%2F%2Fa.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F0824ab18972bd4077557733177899e510eb3096d.jpg'),
            loadImg('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534399739560&di=4535fb90acd623c3e92cb694a00f115b&imgtype=0&src=http%3A%2F%2Fe.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2Ff9198618367adab4bee9208d87d4b31c8601e4c7.jpg')
        ]).then(showImg)
    }
    

    Iterator

    /* 
        16. Iterator
    */
    {
        let arr = ['hello', 'world']
        let map = arr[Symbol.iterator]()
        console.log(map.next()) // {value: "hello", done: false}
        console.log(map.next()) // {value: "world", done: false}}
        console.log(map.next()) // {value: undefined, done: true}
    }
    
    {
        let obj = {
            s: [1, 2],
            e: [8, 9],
            [Symbol.iterator](){
                let self = this
                let index = 0
                let arr = self.s.concat(self.e)
                let len = arr.length
                return {
                    next(){
                        if(index < len) {
                            return {
                                value: arr[index++],
                                done: false
                            }
                        } else {
                            return {
                                value: arr[index++],
                                done: true
                            }
                        }
                    }
                }
            }
        }
    
        for(let k of obj){
            console.log(k) // 1 2 8 9
        }
    }
    

    Generator

    /* 
        17. Generator
    */
    {
        let tell = function* (){
            yield 'a'
            yield 'b'
            return 'c'
        }
        let k = tell()
        console.log(k.next()) // {value: "a", done: false}
        console.log(k.next()) // {value: "b", done: false}
        console.log(k.next()) // {value: "c", done: true}
        console.log(k.next()) // {value: undefined, done: true}
    }
    
    {
        let obj = {}
        obj[Symbol.iterator] = function* (){
            yield 1
            yield 2
            yield 3
        }
        for(let value of obj){
            console.log(value) // 1 2 3
        }
    }
    
    {
        let state = function* (){
            while(1) {
                yield 'A'
                yield 'B'
                yield 'C'
            }
        }
        let status = state()
    
        console.log(status.next())
        console.log(status.next())
        console.log(status.next())
        console.log(status.next())
        console.log(status.next())
        console.log(status.next())
        console.log(status.next())
    }
    
    {
        let draw = function(count) {
            console.info(`剩余${count}次`)
        }
    
        let residue = function* (count){
            while(count>0){
                count--
                yield draw(count)
            }
        }
    
        let start = residue(5)
        let btn = document.createElement('button')
        btn.id = 'start'
        btn.textContent = '点击'
        document.body.appendChild(btn)
        document.getElementById('start').addEventListener('click', function(){
            start.next()
        }, false)
    }
    
    {
        // 长轮询
        let ajax = function* (){
            yield new Promise(function(resolve, reject){
                setTimeout(function(){
                    resolve({code: 0})
                },400)
            })
        }
    
        let pull = function(){
            let generator = ajax()
            let step = generator.next()
            step.value.then(function(res){
                if(res.code != 0){
                    setTimeout(function(){
                        console.log('wait')
                        pull()
                    },1000)
                } else {
                    console.log(res)
                }
            })
        }
    
        pull()
    }
    

    Decorators

    /* 
        18. Decorators
        第三方库: core-decorators
    */
    {
        let readonly = function(target, name, descriptor){
            console.log(target)
            descriptor.writable = false
            return descriptor
            // target 修饰的目标对象
          // name 方法名
          // descriptor对象值如下
          // {
          //   value: specifiedFunction,
          //   enumerable: false,
          //   configurable: true,
          //   writable: true
          // };
          // 可以通过修改descriptor描述器来修改要
        }
    
        class Test{
            @readonly
            time(){
                return '2018-08-08'
            }
        }
    
        let test = new Test()
    
        test.time = function(){
            console.log('tttttttt')
        }
        console.log(test.time())
    }
    
    {
        let typename = function(target, name, descriptor){
            target.name = 'hello'
        }
        @typename
        class Test{}
        console.log(Test.typename)
    }
    
    {
        let log = (type) => {
            return function(target, name, descriptor){
                let src_method = descriptor.value
                descriptor.value = (...arg) => {
                    src_method.apply(target, arg)
                    console.info(`log ${type}`) // 业务
                }
            }
        }
    
        class AD{
            @log('show')
            show(){
                console.info('ad is show')
            }
            @log('click')
            click(){
                console.log('ad is click')
            }
        }
    
        let ad = new AD()
        ad.show()
        ad.click()
    }
    

    模块化

    /* 
        19. 模块化
    */
    {
        export let a = 123
        export function test(){
            console.log('test')
        }
        export class Test{
            test(){
                console.log('test')
            }
        }
    
        import { a} from '...'
        import { a, test, Test} from '...'
        import * as demo from '...'
    }
    
    {
        let a = 123
        function test(){
            console.log('test')
        }
        class Test{
            test(){
                console.log('test')
            }
        }
        export default {
            a,
            test,
            Test
        }
    
        import demo from '...'
    }
    

    async / await

    /*
        async
        await
        async关键字告诉JavaScript编译器对于标定的函数要区别对待。当编译器遇到await函数的时候会暂停。它会等到await标定的函数返回的promise。该promise要么得到结果、要么reject
    */
    async function getSum() {
        let s1 = new Date()
        // let a = await getNum(2)      // 执行时间1s
        // let b = await getNum(3)      // 执行时间1s
        let [a, b] = await Promise.all([getNum(2), getNum(3)])      // 执行时间1s
        let s2 = new Date()
        // return a+b
        console.log(a+b)
        console.log('运行时间', s2 - s1)
    }
    
    function getNum(num) {
        return new Promise((resolve)=>{
            setTimeout( ()=>{ 
                console.log(num**2)
                resolve(num**2) 
            }, 1000)
        })
    }
    // getSum().then( console.log )  // 如果你想获取一个async函数的结果,你需要使用Promise的then语法
    getSum()        // 执行时间2s
    

    相关文章

      网友评论

          本文标题:超详细 ES6 代码段

          本文链接:https://www.haomeiwen.com/subject/jjnubftx.html