nclu
nclu

Reputation: 1059

Adding json stringify to the javascript object prototype

I'd sure like to be able to add this:

Object.prototype.toJson = function() { this.toJson = undefined; return JSON.stringify(this); }

But it gets all circular reference-y. I still want to be able to write .toJson() all over the everywhere.

Upvotes: 2

Views: 370

Answers (1)

Paul Sweatte
Paul Sweatte

Reputation: 24617

Seems to work fine.

Object.prototype.toJson = function() { this.toJson = undefined; return JSON.stringify(this); }

The error actually seems to come in when other libraries are later loaded. Moment.js and KendoUI both are triggering the circular reference. At this point I'm thinking that modifying the Object prototype isn't a very good idea. It'd be nice if objects could just serialize themselves and handle circularity in some magical elegant fashion

Upvotes: 1

Related Questions