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

后端 未结 5 1002
温柔的废话
温柔的废话 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:35

    It's impossible without the help of the object itself. For example, how would you serialize the result of this expression?

    (function () {
      var x; 
      return {
          get: function () { return x; },
          set: function (y) { return x = y; }
        };
    })();
    

    If you just take the text of the function, then when you deserialize, x will refer to the global variable, not one in a closure. Also, if your function closes over browser state (like a reference to a div), you'd have to think about what you want that to mean.

    You can, of course, write your own methods specific to individual objects that encode what semantics you want references to other objects to have.

提交回复
热议问题