Search code examples
javascriptecmascript-6generator

Can there be generator getters in classes?


I mean getters that are generators. All this is ES6+ I believe. Like this maybe.

class a {
    get *count() {
        let i = 10;
        while(--i) yield i;
    }
}

let b = new a;
for(const i of b.count)
    console.log(i);

That doesn't work through, I am placing the asterisk wrong (that is if this is possible at all)

unexpected identifier *


Solution

  • There is no shorthand notation for this. You can however return a generator from a getter property without any difference:

    function* countdown(i) {
        while(--i) yield i;
    }
    class a {
        get count() {
            return countdown(10);
        }
    }
    

    I would recommend to avoid this though. Getters that return distinct stateful objects on consecutive calls can be quite confusing.