I have a class which has two properties, foo
and bar
:
class MyClass{
constructor() {
this.foo = 4;
this.bar = 5;
}
}
Now I want to create a generator. This generator uses foo and far to calculate the next element to yield, so I would like my generator to be encapsulated inside the class.
Making a function generator outside the class is no problem according to the docs. However, using the token function*
inside a class leads to an unexpected token function*
error.
class MyClass{
constructor() {
this.foo = 4;
this.bar = 5;
}
function* myGenerator() {
let index = this.foo;
while(index < this.bar) {
yield index++;
}
}
}
Can generators be created inside classes?
I can create the generator outside the class and pass foo and bar as parameters, but I feel this breaks encapsulation, since the generator is clearly something that should belong to the class.
What are my options here?
The syntax is
*mygenerator() {
// the code
}
You don't put function
before class methods in the class declaration for ordinary functions either.