Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 *

like image 694
Achshar Avatar asked Jun 24 '16 00:06

Achshar


People also ask

What does .get do in Javascript?

The get syntax binds an object property to a function that will be called when that property is looked up.

What is the purpose of getter and setter methods in Javascript?

Getters and setters allow you to define Object Accessors (Computed Properties).

What type of function can have its execution suspended and then resumed at a later point?

Generators are function executions that can be suspended and resumed at a later point. Generators are useful when carrying out concepts such as 'lazy execution'. This basically means that by suspending execution and resuming at will, we are able to pull values only when we need to.


1 Answers

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.

like image 66
Bergi Avatar answered Oct 18 '22 03:10

Bergi