-1

Consider this simple generator function defined on Object.prototype:

Object.prototype.defineProperty(Object.prototype, 'pairs', {
    enumerable: false,
    * value( ) {
        for (const key in this)
            yield [ key, this[key] ];
} });

Of course, it could be used like this:

const object = { goats_teleported: 42 };

for (const [ key, value ] of object.pairs());

But I wonder if there any way to assign pairs function to object prototype, so it will be automaticly fired in for-of loop without explicit call; just like this:

for (const [ key, value ] of object);

Any ideas?

3 Answers3

2
   Object.prototoype[Symbol.iterator] = function* pairs() {
     //...
   };

But be aware that this could cause side effects everywhere. This shouldn't be used in production (or at least, on your own risk ;)).

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
2

Put the generator on Object.prototype[Symbol.iterator]:

Object.prototype[Symbol.iterator] = function* pairs() {
  for (const key in this) yield [ key, this[key] ];
};
const object = { goats_teleported: 42, foo: 'fooval' };

for (const [ k, v ] of object) {
  console.log(k, v);
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

in ES6 you can use Symbol.iterator to define custom iterator for prototype. See here

zoryamba
  • 196
  • 11