开发者

How to derive a JSON string of JavaScript function's properties (and vice versa)?

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开发者_如何学C 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.


i am not sure why you want custom to_json and from_json methods but if you want to just get the details of public variables of an object with its data then you can use JSON.stringify without any problem and it will also handle nesting of the objects, like this

function Object1() {
  this.var1;
  this.var2;
  this.var3;
  this.var4;

  this.method1 = function() {
    this.var3 = this.var1 + this.var2;
  }
}

var obj1 = new Object1();
obj1.var1 = 1;
obj1.var2 = 5;
obj1.var4 = new Object1();
obj1.var4.var1 = 2;
obj1.var4.var2 = 3;
obj1.method1();
obj1.var4.method1();

JSON.stringify(obj1);

so after executing this you will get "{"var1":1,"var2":5,"var4":{"var1":2,"var2":3,"var3":5},"var3":6}"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜