Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected token function* when creating a generator inside a class

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

The syntax is

  *mygenerator() {
    // the code
  }

You don’t put function before class methods in the class declaration for ordinary functions either.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading