While I have come across similar inquiries before, I am still unclear on whether they were answered satisfactorily - perhaps I'm just not grasping it well enough, my apologies.
I am aiming for the convenience and clarity of having my own object named CardboardBox()
. This object will solely contain data without any code. My goal is to be able to store this object in a database and retrieve it later, while understanding that it will be classified as type Object()
when retrieved. The only method I can think of to determine its original form is:
- Include a member variable
type
that denotes CARDBOARD_BOX - Create a new instance of
CarbardBox()
and utilize a function within the box to transfer the properties fromObject()
to the newCardboardBox()
object
Is there a more efficient approach to accomplish this task? I believe there might be a way to modify the actual type.
function CardboardBox() {
this.type = "CARDBOARD_BOX"
this.name = "No set";
this.populate = new function(obj) {
// populate this object with obj properties
}
var box = new CarboardBox(); // CarboardBox
box.name = "My Box";
send = JSON.stringyfy(box);
.
.
.
obj = JSON.parse(send); // Object
if (obj.type == "CARDBOARD_BOX") {
savedBox = new CardboardBox();
savedBox.populate(obj);
}
Thank you in advance... Steve
[edit] Testing Code Below.
function CardboardBox(n) {
this.name = n;
}
var box = new CardboardBox("My Box");
send = JSON.stringify(box); // JSON CarboardBox()
obj = JSON.parse(send, function fn(obj) { // Object() returned
log("OB: "+obj.type);
return obj.type === 'CardboardBox' ? new CardboardBox(obj) : CardboardBox;
});
console.log(obj);
Output displayed:
OB: undefined utils.js:40
OB: undefined utils.js:40
function CardboardBox(n) {
this.name = n;
}