JSFiddle - React, Tailwind, and code Playground
JavaScript
function Fruit(name, color, seeds) {
this.name = name || "";
this.color = color || "";
this.seeds = seeds || [];
this.eat = function() {
return "eating " + this.name;
}
}
function Seed(size, density, quality) {
this.size = size || 0;
this.density = density || 0;
this.quality = quality || undefined;
this.plant = function() {
return "planting seed";
};
}
function Quality(number) {
this.number = number || undefined;
}
var fruitBowl = [];
var apple = new Fruit("apple", "red", []);
var seeds = [
new Seed("small", "hard", new Quality(78)),
new Seed("small", "soft")
];
var orange = new Fruit("orange", "orange", seeds);
fruitBowl.push(apple);
fruitBowl.push(orange);
function isNative(object) {
if(object == null) {
return true;
}
var natives = [Boolean, Date, Number, String, Object, Function];
return natives.indexOf(object.constructor) !== -1;
}
Object.prototype.serialize = function() {
var injectTypes = function(object) {
if(!isNative(object)) {
object.__type__ = object.constructor.name;
}
for(key in object) {
var property = object[key];
if(object.hasOwnProperty(key) && !isNative(property)) {
injectTypes(property);
}
}
};
var removeTypes = function(object) {
if(object.__type) {
delete object.__type__;
}
for(key in object) {
var property = object[key];
if(object.hasOwnProperty(key) && !isNative(property)) {
removeTypes(property);
}
}
}
injectTypes(this);
var json = JSON.stringify(this);
removeTypes(this);
return json;
};
String.prototype.deserialize = function() {
var rawObject = JSON.parse(this.toString());
var reconstruct = function(object) {
var reconstructed = {};
if(object.__type__) {
reconstructed...