I have been working with a fair bit of JSON parsing and passing in Javascript within Node.js and browsers recently and bumped into this conundrum.
Any objects I created using a constructor, cannot be fully serialized fully via JSON.stringify, UNLESS I initialised all values within the constructor individually! This means my prototype becomes essentially useless in designing these classes.
Can someone shed some light on why the following doesn't serialize as I expect?
var ClassA = function () { this.initialisedValue = "You can see me!" };
ClassA.prototype = { initialisedValue : "You can't see me!", uninitialisedValue : "You can't see me!" };
var a = new ClassA();
var a_string = JSON.stringify(a);
What happens:
a_string == { "initialisedValue" : "You can see me!" }
I would expect:
a_string == { "initialisedValue" : "You can see me!", "uninitialisedValue" : "You can't see me!" }
Update (01-10-2019):
Finally noticed @ncardeli 's Answer, which does allow us to do something like the following to achieve my above requirement (in 2019!):
Replace
var a_string = JSON.stringify(a);
with
var a_string = JSON.stringify(a, Object.keys(ClassA.prototype));
Full code:
var ClassA = function () { this.initialisedValue = "You can see me!" };
ClassA.prototype = { initialisedValue : "You can't see me!", uninitialisedValue : "You can't see me!" };
var a = new ClassA();
var a_string = JSON.stringify(a, Object.keys(ClassA.prototype));
console.log(a_string)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…