[removed] stringify object (including members of type function)

后端 未结 5 1018
温柔的废话
温柔的废话 2020-12-01 10:44

I\'m looking for a solution to serialize (and unserialize) Javascript objects to a string across browsers, including members of the object that happen to be functions. A typ

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 11:24

    Something like this...

    (function(o) {
        var s = "";
        for (var x in o) {
            s += x + ": " + o[x] + "\n";
        }
        return s;
    })(obj)
    

    Note: this is an expression. It returns a string representation of the object that is passed in as an argument (in my example, I'm passing the in an variable named obj).

    You can also override the toString method of the Object's prototype:

    Object.prototype.toString = function() {
        // define what string you want to return when toString is called on objects
    }
    

提交回复
热议问题