Search code examples
javascriptgeneratorprototype

JavaScript generators and their prototype chains


I am toying around with JavaScript generators and have 2 questions based on the following code and its output:

const a = function*(){}(); // Object [Generator] {}
const b = a.__proto__;     // Object [Generator] {}
const c = b.__proto__;     // Object [Generator] {}
const d = c.__proto__;     // {}
const e = d.__proto__;     // {}
const f = e.__proto__;     // null
console.log(a, b, c, d, e, f);

Question 1

It seems like every generator object has its own unique prototype, and they all share a common prototype:

const x = function*(){}();
const y = x.__proto__;
const z = y.__proto__;
console.log(b === y); // false
console.log(c === z); // true

Is my above understanding correct?

Question 2

Since f is null, e is probably Object.prototype:

console.log(e === Object.prototype); // true

However, I can't figure out what d is. Is there a Something.prototype that is equal to d?


Solution

  • In the section GeneratorFunction Objects, there is a figure of the relationships: generator_objects_relationships

    Question 1

    Yes.

    Question 2

    d is an IteratorPrototype. And by the doc:

    The following expression is one way that ECMAScript code can access the %IteratorPrototype% object:

    Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))
    

    It seems that there is not an Iterator such that Iterator.prototype is equal to d.