Search code examples
javascriptmethodsprototypefor-in-loop

Method added to Object.prototype repeats infinite times


I was messing around with the browser console to improve my javascript skills.

When I tried to add a method to Object.prototype, that returns its instance as json, something odd happened:

Right at the end of the method, it jumps back to the for-in loop and execute it again. Over and over again...

It does not return anything and just continues to jump back and repeat.

The code:

Object.prototype.toJSON = function() {
  var tempObj = {}; 
  for (let key in this) {
    if (this.hasOwnProperty(key)) { 
      let value = this[key];
      tempObj[key] = value;
    }
  }
  return JSON.stringify(tempObj); 
}

I know you should not add methods to Object.prototype. (If I'm wrong please correct me)

This is for learning purpose only.

Can you please explain to me, why this method behaves like it does?

I don't want to know, how it would work, but why it does not work. :)

Thank you very much!


Solution

  • Because JSON.stringify() whill check if the object have a method toJSON, it will call toJSON if there have one.

    You replace the origin toJSON to yours, and in your toJSON called JSON.stringify(), so there create a call loop.

    check this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description