Generator Methods

When Chapter 8 introduced generators, you learned how to define a generator on an object literal by prepending a star (*) to the method name. The same syntax works for classes as well, allowing any method to be a generator. Here’s an example:

  1. class MyClass {
  2. *createIterator() {
  3. yield 1;
  4. yield 2;
  5. yield 3;
  6. }
  7. }
  8. let instance = new MyClass();
  9. let iterator = instance.createIterator();

This code creates a class called MyClass with a createIterator() generator method. The method returns an iterator whose values are hardcoded into the generator. Generator methods are useful when you have an object that represents a collection of values and you’d like to iterate over those values easily. Arrays, sets, and maps all have multiple generator methods to account for the different ways developers need to interact with their items.

While generator methods are useful, defining a default iterator for your class is much more helpful if the class represents a collection of values. You can define the default iterator for a class by using Symbol.iterator to define a generator method, such as:

  1. class Collection {
  2. constructor() {
  3. this.items = [];
  4. }
  5. *[Symbol.iterator]() {
  6. yield *this.items.values();
  7. }
  8. }
  9. var collection = new Collection();
  10. collection.items.push(1);
  11. collection.items.push(2);
  12. collection.items.push(3);
  13. for (let x of collection) {
  14. console.log(x);
  15. }
  16. // Output:
  17. // 1
  18. // 2
  19. // 3

This example uses a computed name for a generator method that delegates to the values() iterator of the this.items array. Any class that manages a collection of values should include a default iterator because some collection-specific operations require collections they operate on to have an iterator. Now, any instance of Collection can be used directly in a for-of loop or with the spread operator.

Adding methods and accessor properties to a class prototype is useful when you want those to show up on object instances. If, on the other hand, you’d like methods or accessor properties on the class itself, then you’ll need to use static members.