Assuming I have a JavaScript function like this...
function Object1() {
this.var1;
this.var2;
this.var3;
this.method1 = function() {
this.var3 = this.var1 + this.var2;
}
}
...and create an instance:
var obj1 = new Object1();
obj1.var1 = 1;
obj1.var2 = 2;
obj1.method1();
Based on obj1, I want to create a JSON string from all instance variables of function Object1. Obviously, the expected JSON string should look as follows:
{"var1" : 1, "var2" : 2, "var3" : 3}
Two Questions:
1.) Is there a more elegant way to manually implementing a to_json() method in function Object1 which creates a JSON object of all instance variables and calls JSON.stringify() on that JSON object?
2.) In this regard, is there a more elegant way to create an instance of function Object1 based on a JSON string exemplarily shown above to manually implementing a from_json() method on function Object1 which calls JSON.parse() on that JSON string, iterates over the resulting JSON object and assigns each JSON value to the respective instance variable.
for (var prop in MyObject) { ... }would work, though I'm not sure "foreach"s are supported in all JS implementations. (Docs on For...In)to_jsonimplementation would give you overJSON.stringify(obj1). The serializer works fine on yourObject1instances, and knows to skip functions. What is inelegant?