ES6 generator函数的详解

迭代器的基础用法

function* helloGenerator(){
    yield '我是next1'
    yield '我是next2'
    return 123
}
let res = helloGenerator()
console.log(res.next());
console.log(res.next());
console.log(res.next());
console.log(res.next());
console.log(res.next());
console.log(res.next());

每个对象都有Symbol.iterator属性

let myIterator = {}
myIterator[Symbol.iterator] = function*(){
    yield 1;
    yield 2;
    yield 3;
    yield 4;
}
console.log([...myIterator]);//[1,2,3,4]
function* helloGenerator(){
    let y1 = yield 'hello'
    console.log(y1);
    yield 'world'
    return 123
}

let res = helloGenerator()
console.log(res.next());
console.log(res.next(123));//传入值y1=123
console.log(res.next());

迭代器得异常捕获

// 函数体外抛出异常在gennerator函数内部去获取
    // throw函数接收的参数 通过catch去获取
    let g = function*(){
        try{
            yield
        } catch(error){
            console.log(error);
            
        }
            
    }
    let res = g()
    res.next()
    res.throw('错误')

    // generator函数体内抛出异常 也可以在函数体外的catch获取
    let g = function*(){
       yield;
            
    }
    let res = g()
    res.next()
    try {
        res.throw('错误')
    } catch (error) {
        console.log(error);
        
    }

yield*得用法

function* first(){
        yield 1;
        yield 2;
    }

    function* second(){
        yield 3
        // 在这里调用firstgenerator函数应该怎么做?
        for (let i of first()){
            yield i
        }
        yield 4
    }
    // for...of 循环遍历第二个
    // 上面可以用过 yield* 来替换

    function* second(){
        yield 3
        // 在这里调用firstgenerator函数应该怎么做?
        yield* first()
        yield 4
    }

generator函数this得用法

// 不支持new 现在让你支持new
    function* f(){
        this.a = 123
        yield this.b = 234
        yield this.c = 456
    }

    // let obj = {}
    // let res = f.call(f.prototype)
    // console.log(res.next());
    // console.log(res.next());
    // console.log(res.a);
    // console.log(res.b);
    // console.log(res.c);

    function F(){
        return f.call(f.prototype)
    }

    let res = new F()
   console.log(res.next());
    console.log(res.next());
    console.log(res.a);
    console.log(res.b);
    console.log(res.c);
原创文章 207 获赞 173 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_41181778/article/details/104851532