我将JSON解析为对象数组时遇到问题。
我有三个JavaScript类
我想创建Pet对象数组,然后我想将它作为JSON存储在浏览器本地存储中。
问题:
当我检索JSON并将其解析为对象数组时,元素的原型从Cat或Dog变为Object,因此当我测试时
pets[0] instanceof Cat // always false
pets[0] instanceof Dog // always false
我是否有办法将元素原型保留为原始非对象?
课程:
function Pet(imageUrl, name, soundUrl) {
this.imageUrl = imageUrl;
this.name = name;
this.soundUrl = soundUrl;
this.talk = function() {
};
}
function Cat(imageUrl, name, soundUrl, favoriteFood) {
Pet.apply(this,arguments);
this.favoriteFood=favoriteFood;
}
Cat.prototype=new Pet();
Cat.prototype.constructor = Cat;
function Dog(imageUrl, name, soundUrl, walkingTime) {
Pet.apply(this,arguments);
this.walkingTime=walkingTime;
}
Dog.prototype=new Pet();
Dog.prototype.constructor = Dog;
创建阵列后,我必须将其保存到浏览器本地存储
var pets=[];
var cat = new Cat('imageUrl','name','soundUrl','favoriteFood');
pets.push(cat);
localStorage.setItem('pets', JSON.stringify(pets));
要检索数组:
if (localStorage.getItem('pets') !== null)
{
var pets = JSON.parse(localStorage.getItem('pets'));
}
答案 0 :(得分:4)
是的,在JSON中你只有普通的vanilla对象(和数组)。我可以看到处理这个问题的唯一方法是添加一个额外的属性给出类,然后在解析你的JSON之后,你需要将生成的对象转换为动物(以某种方式赋予它们生命)。 / p>
答案 1 :(得分:3)
@ MauricePerry答案的实施示例:
您希望将Stringify方法添加到Pet类中,该类返回一个vanilla对象,您可以在以后实例化动物对象。
示例:
// add stringify function to your Pet class
function Pet(imageUrl, name, soundUrl) {
...
this.stringify = function () {
var jsonRepresentation = {};
for (attr in this) {
if (typeof this[attr] != "function") {
jsonRepresentation[attr] = this[attr];
}
}
return jsonRepresentation;
};
};
// add a class property to your various pet subclasses
// e.g. Cat.prototype.class = "cat";
// create an instance of Cat
var cat = new Cat('imageUrl','name','soundUrl','favoriteFood');
// get the info to restore the cat instance later on
var animalInfo = cat.stringify();
/*
cat info would be like:
{
"class": "cat",
"imageUrl": "theUrl",
"name": "theName",
"soundUrl": "theSoundUrl",
"favoriteFood": "theFavoriteFood"
}
*/
// then you would store the info to localStorage
...
// later you could retrieve you cat instance like so
var restoredAnimal;
switch(animalInfo.class) {
case "cat":
restoredAnimal = new Cat(animalInfo.imageUrl, animalInfo.name, animalInfo.soundUrl, animalInfo.favouriteFood)
break;
default:
console.log('there is no such animal');
}