Subj : Re: object serialization To : netscape.public.mozilla.jseng From : Jens Thiele Date : Fri Mar 26 2004 01:12 am a first hack to get serialization working in "pure" javascript - intended for "pure" javascript objects) - keeping the prototype (__proto__ field) right - keep graph relationships the hash function is shit - is there any way to get a hashvalue for an object (perhaps based on its pointer/reference)? karme // a first object serializer hack // based on code from Daniel Fournier ( thanks!) // todo this is shit function hashfunc(obj,key,depth) { /* if (!key) key=''; if (!depth) depth=0; var i,t; for (i in obj) { key+=i; t=typeof(obj[i]); key+=t.substring(0,1); if (t == 'string') key+=obj[i].substring(0,3); if (t == 'number') key+=obj[i]; else if ((depth<3)&&(t == 'object')) key+=hashfunc(obj[i],key,depth+1); if (key.length>60) return key; } return key;*/ return obj.toSource(); } function emptyproto(p) { for (a in p) return false; return true; } function Serializer() {}; // enter new scope Serializer.prototype._push=function(v){ this.scope.push(v); this.fqscope+=v; } // leave scope Serializer.prototype._pop=function(){ this.scope.pop(); var r=''; for (var i=0;i0) objectString+=','; c++; this._push("["+k+"]"); objectString += this._serialize(object[k]); } } } else { // object closeSymbol = '}'; objectString += '{'; var c=0; for (var k in object) { // test if this member comes from our prototype if (object.__proto__[k]!=object[k]) { if ((stored=this._getSerialized(object[k]))) this.append+=this.fqscope+"."+k+"="+stored+";\n"; else{ if (c>0) objectString+=','; c++; this._push("."+k); objectString += k + ':' + this._serialize(object[k]); } } } // serialize prototype if ((object.__proto__)&&(!emptyproto(object.__proto__))) { if ((stored=this._getSerialized(object.__proto__))) this.append+=this.fqscope+".__proto__="+stored+";\n"; else{ if (c>0) objectString+=','; c++; this._push(".__proto__"); objectString += "__proto__" + ':' + this._serialize(object.__proto__); } } } objectString += closeSymbol; this._pop(); return objectString; } // graph test foo={a:4}; graph={x:foo, y:foo}; eval(new Serializer().serialize(graph, 'graph2')); graph2.x.a=77; // should print 77 print((graph2.y.a==77) ? "Test passed" : "Test failed"); .