简体   繁体   中英

Javascript: how to save object with private fields to file?

I've tries to save an object like a string and for this I use JSON.stringify() but it picks up only public fields.

How to grab privates?

<html>
<head>
    <title></title>
</head>
<body>

    <script>
        function Class1() {
            var prop1 = 1;
            this.prop2 = 2;
        };

        var inst1 = new Class1();

        var str = JSON.stringify(inst1);

        console.log(str);
    </script>
</body>
</html>

the output is: {"prop2":2}

and I want {"prop1":1, "prop2":2}

The "private property" is not actually found inside your object, it is a variable in the constructor's scope only. If you interact with it via methods, then it will be available to those methods via closures.

If you want to serialize an object with its private properties, you need to write your own serialization and deserialization methods that can access the private properties (via closures) as explained above.

Some code to get you started:

function Class1(opt_prop1, opt_prop2) {
  var prop1 = opt_prop1 || 1;
  this.prop2 = opt_prop2 || 2;

  this.toJSON = function() { 
    return { prop1 : prop1, prop2 : this.prop2 }; 
  };
}

Class1.fromJSON = function(str) {
  var obj = JSON.parse(str);
  return new Class1(obj.prop1, obj.prop2);
}

Note that while the fromJSON method can be a normal function (which i just happened to make "static" to the Class1 class in the traditional OOP sense by adding it to the constructor), the toJSON method needs to access the local variables of the constructor, so it must be defined inside the constructor.

As mentioned by @JamesHill in the comment, if present a toJSON method can simplify the serialization implementation. You simply need to return a plain object which contains the properties you want serialized (which should be the properties that allow you to restore the instance in the deserialization process).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM