This is an example program that shows limitations of stringify() on class objects in JavaScript. Notice that private members and methods are not copied.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>XoaX.net's Javascript</title> <!-- Supply a transparent 1x1 favicon --> <link rel="icon" href="data:,"> <script type="text/javascript" src="StringifyClassObjects.js"></script> </head> <body onload="Initialize()"> <h1>Stringify()</h1> <span id="idObject1"></span> <h2>Versus</h2> <h1>PrintAnObject()</h1> <span id="idObject2"></span> </body> </html>
function Initialize() {
let qObject = new CMan();
let qElement = document.getElementById("idObject1");
// All member functions, whether public or private, are ignored, as well as private members.
let sJson = JSON.stringify(qObject, (key, value) => {
if (typeof value === "function") {
return value.toString();
}
return value;
});
qElement.innerHTML = sJson;
document.getElementById("idObject2").innerHTML = PrintAnObject("qObject", qObject);
}
class CMan {
#mdAge;
constructor() {
this.msName = "Jesus Christ";
this.#mdAge = 30.5;
}
#IsGod() {
return true;
}
IsMan() {
return true;
}
}
function PrintAnObject(sName, qObject, sPre = "") {
let sOutput = typeof(qObject) + " " + qObject.constructor.name + ": " + sName + '<br />';
for (let sProperty in qObject) {
if (typeof(qObject[sProperty]) == "object") {
sOutput += PrintAnObject(sProperty, qObject[sProperty], sPre + " ");
} else {
sOutput += sPre+" "+typeof(qObject[sProperty])+': '+sProperty+' = '+qObject[sProperty]+'<br />';
}
}
return sPre + sOutput;
}© 20072026 XoaX.net LLC. All rights reserved.