如何更改Javascript对象的类型?

时间:2017-04-16 16:33:01

标签: javascript json object prototype

我正在构建一个基于网页的文本冒险游戏,如Hitchhiker的Galaxy指南或Zork系列。我将此游戏中的对象保存在localStorage中,例如位置或玩家数据,以便玩家可以继续进行。

我正在使用CircularJSON对这些对象中的循环引用进行字符串化以保存它们。

但是,解析这些对象时,它们是默认的对象类型。

这是一个问题,因为区域

等类型的功能
var Area = function (tempdescription, tempinitialDesc, tempobjArr) {
    this.isExplored = false;
    this.description = tempdescription;
    this.objArr = tempobjArr;
    this.paths = [];
    this.initialDesc = tempinitialDesc;
};
Area.prototype.getIndex = function (tempstr) {
    if(thePlayer.playerLocation.objArr.length > 0) {
        for(var i = 0; i < thePlayer.playerLocation.objArr.length; i++) {
            if(thePlayer.playerLocation.objArr[i].name.indexOf(tempstr) != -1) {
                return i;
            }
        }
    }
    return -1;
};

播放器

var Player = function (defaultLocation) {
    this.inv = []; // an array of game objects
    this.playerLocation = defaultLocation; // the player's current location
    this.moveCount = 0;
    this.score = 0;
};

Player.prototype.getIndex = function (tempstr) {
    if(thePlayer.inv.length > 0) {
        for(var i = 0; i < thePlayer.inv.length; i++) {
            if(thePlayer.inv[i].name.indexOf(tempstr) != -1) {
                return i;
            }
        }
    }
    return -1;
};

由我创建,需要出现在每个对象顺序中,以便我的其他代码能够工作。

我需要以简单的方式更改几个对象的类型(如果存在),因为当我保存这些对象时,在游戏完成时可能会有几十个对象。

有没有办法改变Javascript对象的类型?

1 个答案:

答案 0 :(得分:0)

选项#1(使用ES2015): const newObject = Object.setPrototypeOf(oldObject, Player.prototype)

这很慢,请查看documentation

  

警告:根据现代JavaScript引擎优化属性访问的性质,在每个浏览器和JavaScript引擎中更改对象的[[Prototype]]是非常慢的操作。

这是......的替代品。

选项#2(已弃用): oldObject.__proto__ = Player.prototype

选项#3: const newObject = new Person(/* Use the properties of oldObject */)

相关问题