JSON为什么无法保存对象的功能?

问题描述:

在我的游戏中,我将所有对象都转换为JSON,然后将其保存到文件中,以保存当前状态.有些对象(例如敌人)具有功能,但是JSON无法保存功能!有替代方案还是解决方案?

In my game, I save the current state by converting all the objects to JSON and then saving that to a file. Some objects, like enemies, have functions on them, but JSON can't save functions! Is there an alternative or a solution?

var Enemy = {
  toJSON: function () {
    // pack it up
  },
  fromJSON: function (json) {
    // unpack it.
  },
  /* methods */
};

var e = Object.create(Enemy);
var json = JSON.stringify(e);
var same_e = Enemy.fromJSON(json);

.toJSON方法是JSON.stringify的标准接口,它将查找此方法并调用它(如果存在),它将对返回的对象进行字符串化.

the .toJSON method is a standard interface of JSON.stringify it will look this method and call it if it exists, it will stringify the returned object.

.fromJSON方法只是您的Enemy对象的命名构造器.

The .fromJSON method is just a named constructor for your Enemy object.

具体示例 JSfiddle

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);

元选项:

一个元选项是将类名称写入对象

A meta option would be to write the class name to the object

Game.Enemy = {
  ...
  class: "Enemy"
};

然后,当您加载所有json数据时,您只需执行

Then when you load all your json data you just do

var instance = Game[json.class].fromJSON(json);