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:
{"me":this}
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.me = this;
return this;
}
}.me()
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.me = this; return this;},
"alsoMe":function(){this.alsoMe = this; return this;},
"subObject":{
"subMe":function(){this.subMe = this; return this;}
}.subMe()
}.me().alsoMe()
1 comment:
thanks. helped a lot.
Post a Comment