Can there be generator getters in classes?

懵懂的女人 提交于 2019-12-29 07:32:12

问题


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 *


回答1:


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.



来源:https://stackoverflow.com/questions/38004152/can-there-be-generator-getters-in-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!