Generator and async Methods

Generators and async functions may be defined as the methods of a class.


//(continues from the example in 8.6.2)
class GermanShepherd extends Dog { // default contructor
  *bark() { // generator
    while (true) {
      console.log('whoaaaf');
      yield;
      console.log('whoaaaf whoaaf');
      yield;
      console.log('whoaaaf whoaaf whoaf');
      yield;
    }
  }

  async sleep() { // async function
    await new Promise(resolve => {
      console.log(this.name + ' has fallen asleep.');
      resolve();
    }).then(() => console.log(this.name + ' seems to have awaken.'));
    console.log('When will ' + this.name + ' sleep again?');
  }
}

var s = new GermanShepherd('Smartie', 3, 'Black');
var sb = s.bark();
sb.next();
sb.next();
s.sleep();
sb.next();
sb.next();

whoaaaf whoaaaf whoaaf Smartie has fallen asleep. whoaaaf whoaaf whoaf whoaaaf Smartie seems to have awaken. When will Smartie sleep again?

In any case, you can omit super() in your subclass, if you omit the constructor altogether in your subclass. A 'hidden' default constructor will be included automatically in your subclass. However, if you do include the constructor in your subclass, super() must be called in that constructor.For a base class, the default constructor is simple:

constructor(){}

For a derived class, the default constructor is:


constructor(...args) {
  super(...args);
}