Friday, January 18, 2008

JSON Recursion -- Making a Self Reference

I have been working on a simple JSON library in Java which will allow me to serialize a JSON string. I'm pretty satisfied with the results so far, and I intend to release the code, however, until today, there was one thing that threw me for a loop. Writing JSON including a self reference. Here's the problem

When you write the following JSON syntax:


You expect that when you access the 'me' property, it would give a reference to that object. However, what you get instead is a reference to the Window object. This happens because the closures that javascript has assigns the 'this' to the Window because during the construction of the new object, the new object doesn't yet exist, and 'this' still refers to the Window. Not what we wanted.

Here's the fix:
"me":function(){ = this;
return this;

Instead of assigning the 'me' attribute to 'this' right away, we construct the object, setting the 'me' attribute to a function. The 'me' function re-assigns its own value, and in effect, kind of self-destructs. Finally, we make the 'me' function return a reference to 'this'. 'me' is now assigned a reference to itself.

This method works within an eval as well. It also nests pretty well too. Here's a more complicated example, with a sub-object containing a self reference, as well as multiple self-references:
"me":function(){ = this; return this;},
"alsoMe":function(){this.alsoMe = this; return this;},
"subMe":function(){this.subMe = this; return this;}

1 comment:

Anonymous said...

thanks. helped a lot.