2013-10-08 27 views
2

我确实希望能够补充一点:添加JSON字符串化的JavaScript对象原型

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

但它可以让所有的循环引用-Y。我仍然希望能够遍布各处编写.toJson()。

+0

=未定义在那里。那是在我的剪贴板中结束了。 – nclu

+0

只要放下'this.toJson = undefined;'...你想用这个完成什么? –

+0

没有它仍然yeilds: 未捕获TypeError:将圆形结构转换为JSON 这是一个跛脚的尝试,使其消失。 – nclu

回答

1

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

也许用的是this.toJson