It isn't possible to stringify an instance of a constructor and for it to still be an instance of the constructor after turning it back into an object.
Instead, you would need to give the Task instance a method that outputs a json string that you can store, then when you want it to be an instance of Task again, you can create a new instance.
function Task(description) {
var _description = description;
this.getDescription = function() {
return _description + '(possibly modified?)';
}
this.stringify = function () {
return JSON.stringify({
description: this.getDescription(),
_description: _description
});
}
}
var task = new Task('wash car');
console.log(task.getDescription()); // 'wash car (possibly modified?)'
var json = task.stringify();
console.log(json); // {"description": "wash car (possibly modified?)", "_description": "wash car"}
var taskAgain = new Task(JSON.parse(json)._description);
console.log(taskAgain.getDescription()); // 'wash car (possibly modified?)'
I added the " (possibly modified?)"
to demonstrate why it is important to pass both the result of getDescription
and the string stored in _description
. if getDescription
never changes the description, there is no need to have getDescription
in the first place which greatly simplifies this whole process.
function Task(description) {
this.description = description;
}
var task = new Task('wash car');
console.log(task.description); // wash car
var json = JSON.stringify(task);
console.log(json); // {"description": "wash car"}
console.log(JSON.parse(json).description); // wash car
var taskAgain = new Task(JSON.parse(json).description);
console.log(task.description); // wash car