Best way to serialize/unserialize objects in JavaScript?

前端 未结 8 1425
忘掉有多难
忘掉有多难 2020-11-27 13:53

I have many JavaScript objects in my application, something like:

function Person(age) {
    this.age = age;
    this.isOld = function (){
        return thi         


        
8条回答
  •  孤独总比滥情好
    2020-11-27 14:12

    JSON has no functions as data types. You can only serialize strings, numbers, objects, arrays, and booleans (and null)

    You could create your own toJson method, only passing the data that really has to be serialized:

    Person.prototype.toJson = function() {
        return JSON.stringify({age: this.age});
    };
    

    Similar for deserializing:

    Person.fromJson = function(json) {
        var data = JSON.parse(json); // Parsing the json string.
        return new Person(data.age);
    };
    

    The usage would be:

    var serialize = p1.toJson();
    var _p1 = Person.fromJson(serialize);
    alert("Is old: " + _p1.isOld());
    

    To reduce the amount of work, you could consider to store all the data that needs to be serialized in a special "data" property for each Person instance. For example:

    function Person(age) {
        this.data = {
            age: age
        };
        this.isOld = function (){
            return this.data.age > 60 ? true : false;
        }
    }
    

    then serializing and deserializing is merely calling JSON.stringify(this.data) and setting the data of an instance would be instance.data = JSON.parse(json).

    This would keep the toJson and fromJson methods simple but you'd have to adjust your other functions.


    Side note:

    You should add the isOld method to the prototype of the function:

    Person.prototype.isOld = function() {}
    

    Otherwise, every instance has it's own instance of that function which also increases memory.

提交回复
热议问题