0

Let's consider this illustrative example:

function Test() {
    this.a = 3;
    this.b = 4;
    this.c = function(c, d) {
        return c + d;
    }
}

I would like to be able to convert this object into JSON and whenever needed to reload it along with the function(s) it has. JSON.stringify(new Test()) will ommit this.c.

Is it possible to do a smart save, saving the functions as well as the object and a smart load?

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • 1
    You cannot convert *any* JavaScript object to JSON. There are a variety of characteristics that JavaScript objects may have that cause them to be unrepresentable as JSON. – Pointy Sep 11 '16 at 17:50
  • @Pointy, I was thinking of something like function gatherFunctions(obj) {var funcs = {};for (var member in obj) {if (typeof obj[member] === "function") {funcs[member] = obj[member] + "";}}return funcs;}, but the question was marked as a duplicate, so I will do the research for myself only and will not post it here, as it seems to be unwelcome. – Lajos Arpad Sep 11 '16 at 17:58
  • Do read the content of the linked duplicate - there's nothing wrong with posting questions that are marked as duplicates, because they may make it easier for people to find the answers in the future. In this case, that linked question has an answer that provides some possibilities, and also explains that serializing functions cannot be done reliably in all cases. – Pointy Sep 11 '16 at 18:01
  • @Pointy, I have read that, but the answer is not generic-enough for me. – Lajos Arpad Sep 11 '16 at 18:07
  • Well, the problem is that there really is no 100% guaranteed way to do it. You have to create your own tool that satisfies your particular requirement. – Pointy Sep 11 '16 at 18:08
  • @Pointy, I intended to ask my question and while waiting for answers write my own tool, so we would share a lot of ideas which would result in a bullet-proof, yet simple and succint tool. But in this case my question was marked as duplicate, so I will write the tool on my own and will leave this question to rot ;) – Lajos Arpad Sep 11 '16 at 18:13
  • You cannot make a "bullet-proof" serializer, because you cannot access all the information needed about the environment of functions attached to the object being serialized. You can get the source text of the function, but you cannot find out about the closure in which the function was created. – Pointy Sep 11 '16 at 19:03
  • @Pointy, that is true, by "bullet proof" I mean handling what is possible. – Lajos Arpad Sep 12 '16 at 08:01

0 Answers0