💾IteratorPrototype

JSiterationiterator ⟩ IteratorPrototype

💾 replit:IteratorPrototype

// ⭐ %IteratorPrototype%
// -------------------------------------------------------
//   prototype of all built-in iterators
//
//   const IteratorPrototype = {
//       [Symbol.iterator]() { return this },
//   };
//
// Note: 
//   in ECMAScript spec, internal objects are enclosed
//   in percent (%) signs.

// ⭐ %IteratorPrototype% is not directly accessible, 
//    but we can access it indirectly (from any built-in iterator).
//
// ⭐ array iterator -> ArrayIterator -> IteratorPrototype
const IteratorPrototype = Object.getPrototypeOf(    // IteratorPrototype
    Object.getPrototypeOf(                          // ArrayIterator
        [][Symbol.iterator]()    // ⭐ let empty array make an iterator
    )
);

💈範例:

// what is the prototype of an array iterator?
let arrayIterator = [][Symbol.iterator]();
let proto = Object.getPrototypeOf(arrayIterator);
console.log(proto);              // Object [Array Iterator] {}

;[
    // `IteratorPrototype` is the prototype of ??? iterator ?
    'abc'[Symbol.iterator](),    // true (String iterator)
    [].keys(),                   // true (iterator of Array keys)
    new Map().entries(),         // true (iterator of Map entries)
    (function*() { })(),         // true (generator: iterable iterator)
    'aaa'.matchAll(/a/g),        // true (iterator of all results)

].forEach(iterator => {
    let ans = IteratorPrototype.isPrototypeOf(iterator);
    console.log(ans);
});

Last updated