Has anyone implemented Mozilla\'s Object.toSource() method for Internet Explorer and other non-Gecko browsers? I\'m looking for a lightweight way to serialize simple object
In order to take this a little further: when you send something - to work on - a receiver must get it and be able to work on it. So this next bit of code will do the trick - adapted from the previous answer by Eliran Malka.
// SENDER IS WRAPPING OBJECT TO BE SENT AS STRING
// object to serialize
var s1 = function (str) {
return {
n: 8,
o: null,
b: true,
s: 'text',
a: ['a', 'b', 'c'],
f: function () {
alert(str)
}
}
};
// test
s1("this function call works!").f();
// serialized object; for newbies: object is now a string and can be sent ;)
var code = s1.toString();
// RECEIVER KNOWS A WRAPPED OBJECT IS COMING IN
// you have to assign your wrapped object to somevar
eval('var s2 = ' + code);
// and then you can test somevar again
s2("this also works!").f();
Be aware of the use of eval
. If you own all code being transferred: feel free to use it (although it can also have disadvantages). If you don't know where the source is coming from: it's a no-no.
javascript object tosource stringify eval