var Enemy = { toJSON: function () {
The .toJSON method is the standard JSON.stringify interface, it will look for this method and call it, if it exists, it will truncate the returned object.
The .fromJSON method is just a named constructor for your Enemy object.
Concrete JSfiddle Example
var Enemy = { constructor: function(name, health) { this.health = health || 100; this.name = name; }, shootThing: function (thing) { }, move: function (x,y) { }, hideBehindCover: function () {}, toJSON: function () { return { name: this.name, health: this.health }; }, fromJSON: function (json) { var data = JSON.parse(json); var e = Object.create(Enemy); e.health = data.health; e.name = data.name; return e; } } var e = Object.create(Enemy); e.constructor("bob"); var json = JSON.stringify(e); var e2 = Enemy.fromJSON(json); console.log(e.name === e2.name);
Meta option:
The meta parameter would have to write the class name for the object
Game.Enemy = { ... class: "Enemy" };
Then when you load all your json data, you just do
var instance = Game[json.class].fromJSON(json);
source share