Si tengo un objeto construido, y ese objeto tiene una propiedad de matriz, y defino el Symbol.iterator del prototipo para que apunte al Symbol.iterator de la matriz interna, de alguna manera no obtengo el mismo iterador.
He aquí un ejemplo mínimo:
const thing = function () { this.internalArray = [1, 2, 3, 4, 5]; } Object.defineProperty(thing.prototype, Symbol.iterator, { get: function () { return this.internalArray[Symbol.iterator]; } }); const test = new thing(); const a = test.internalArray[Symbol.iterator](); const b = test[Symbol.iterator](); console.log(a); // => Array Iterator {} console.log(b); // => Array Iterator {} console.log(a.next()); // => { value: 1, done: false } console.log(b.next()); // => { value: undefined, done: true }No puedo entender por qué sucede esto.
Al devolver el iterador, debe vincularlo a la instancia de matriz this.internalArray ; de lo contrario, todo lo que tiene es Array.prototype[Symbol.iterator] , que no iterará sobre nada que esté directamente en el objeto de test .
const thing = function () { this.internalArray = [1, 2, 3, 4, 5]; } Object.defineProperty(thing.prototype, Symbol.iterator, { get: function () { return this.internalArray[Symbol.iterator].bind(this.internalArray); } }); const test = new thing(); const b = test[Symbol.iterator](); console.log(b); // => Array Iterator {} console.log(b.next()); // => { value: undefined, done: true }