I’ve been using dean edwards base.js (http://dean.edwards.name/weblog/2006/03/base/) to organise my program into objects ( base.js is amazing btw, if you havent used it before !).Anyway, my question is generic and you don’t have to know base.js to know my answer.
I have a property in one of my objects called ref which is a reference to a DOM element, and this object is meant to be saved as JSON using JSON.stringify, but as you can imagine since DOM elements are circular structure, I won’t be able to convert the object into JSON.
Now to get around this problem I have a method called html() which is meant to return the ref property, but I need to have ref as a private property which is only accessible from within the object, and hence won’t be sent to stringify.
What’s the best way to do that?
You probably know that you cannot have private properties in JavaScript.
Interestingly, if you pass an object to
JSON.stringifywhich has a methodtoJSON,JSON.stringifywill automatically call that method to get a JSONable representation of that object. So all you have to do is implement this method.For example you can create a shallow copy of the object which only contains the properties you want to copy:
DEMO
Another way would be to use a custom replacer function, but it might be more difficult to control which
refto exclude and which one to keep (if different objects haverefproperties):DEMO