JavaScript generators and their prototype chains
In the section GeneratorFunction Objects, there is a figure of the 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
.
Yes. Let's break this down some more:
function* g() {} // a generator function
const GeneratorFunction = Object.getPrototypeOf(g).constructor;
console.assert(Object.getPrototypeOf(GeneratorFunction) == Function);
const Generator = GeneratorFunction.prototype;
console.assert(Object.getPrototypeOf(Generator) == Function.prototype);
const ArrayIteratorPrototype = Object.getPrototypeOf([].values());
const a = g(); // a generator
console.assert(a instanceof g);
const b = Object.getPrototypeOf(a); // a prototype object
console.assert(b == g.prototype);
const c = Object.getPrototypeOf(b); // the Generator.prototype
console.assert(c == Generator.prototype);
const d = Object.getPrototypeOf(c); // the Iterator.prototype
console.assert(d == Object.getPrototypeOf(ArrayIteratorPrototype));
const e = Object.getPrototypeOf(d); // the Object.prototype
console.assert(e == Object.prototype);
const f = Object.getPrototypeOf(e); // null
console.assert(f == null);
The object d
you were looking for is the prototype object shared by all iterators (array iterators, map iterators, set iterators, string iterators etc), including generators. There is not global Iterator
(yet) just as there are no global Generator
or GeneratorFunction
.