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

cor*_*zza 5 javascript json node.js

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

Ray*_*nos 7

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);
Run Code Online (Sandbox Code Playgroud)

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

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

具体例子 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);
Run Code Online (Sandbox Code Playgroud)

元选项:

元选项是将类名写入对象

Game.Enemy = {
  ...
  class: "Enemy"
};
Run Code Online (Sandbox Code Playgroud)

然后,当您加载所有的json数据时,您就可以了

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