Can I smuggle custom constructors in the toJSON overriden method?

1k Views Asked by At

The JSON.stringify behavior can be altered by overriding .toJSON method:

var obj = {toJSON: function() {return [1,2,3];}};
var x = JSON.stringify(dd); 
console.log(x);  // "[1,2,3]"
JSON.parse(x);   // [1,2,3]

I'd like to pass the javascript pseudo-class instances (objects inheriting from other objects). However it doesn't seem possible to add any function call in the data:

function Pseudoclass(x) {
    this.x = x;
    //More operations
}

If you return function, .stringify fails. Not talking about the fact that it doesn't seem very possible to pass the class properties:

//JSON.stringify(inst) will be undefined
Pseudoclass.prototype.toJSON = function() { 
    //If converted to string, the function loses variables from this scope
    return function() {return new Pseudoclass();};
}

If you return string, it's encoded as string:

//JSON.stringify(inst) returns "\"Pseudoclass.fromJSON(6)\"" if x was 6
Pseudoclass.prototype.toJSON = function() { 
    return "Pseudoclass.fromJSON("+this.x+")";
}

So does anybody has any hacks in mind? I'd use this to pass prepared class instances to Worker - the only option there is figuring this JSON question or a custom format.

Don't forget that the constructor call may not be the only way. All I need is that the object inherits from my predefined object!

0

There are 0 best solutions below