What's the purpose of an asterisk (*) in ES6 generator functions

后端 未结 2 1023
半阙折子戏
半阙折子戏 2021-02-01 01:03

Can someone explain to me: why are generator functions in ES6 marked by asterisk symbol?

For example, instead of:



        
2条回答
  •  没有蜡笔的小新
    2021-02-01 01:54

    Empty generators (with no body) are not disallowed; so should unStarredFunc() follow generator semantics or not?

    For compatibility reasons:

    function yield(x) { return x };
    
    function a() { 
        yield (4+1);
    };
    

    this is syntactically correct but calling .next() would result in an error whereas adding an asterisk to explicitly define a generator would cause .next().value === 5

    detect that someGenerator contains yield operator at parse time

    Some constructs cannot be resolved at parse time:

    function someGenerator(i) { 
        if (glob) 
            return 4; 
        else 
            yield* anotherGen(i);
    }
    

    And of course its simpler to see immediately from the function* definition that its a generator without needing to dig into its source to look for yields.

提交回复
热议问题