问题描述
我问这个问题的原因是因为我想将LocalStorage用于我的对象。正如您可能知道的,当使用LocalStorage时,您必须对对象进行JSON.stringify,然后将它们解析回javascript对象。
the reason I am asking this question is because I want to use LocalStorage for my objects. And as you might know, when using LocalStorage you have to JSON.stringify the objects and then parse them back to javascript objects.
我正在尝试JSON.stringify一个对象使用方法,然后解析它,但我得到的只是一个空对象。
I am trying to JSON.stringify an object with methods and then parse it back but all I get is an empty object.
请看一下这段代码。
Person.js
function Person(name, telePhone) {
this.getName = function () {
return name;
}
this.setName = function (_name) {
name = _name;
}
this.getTelePhone = function () {
return telePhone;
}
this.setTelePhone = function (_telePhone) {
telepPhone = _telePhone;
}
};
Javascript.js
window.onload = function () {
var name = "John";
var telePhone = "073-2335662";
var personObject = new Person(name, telePhone);
console.log(personObject);
// returns: Person
console.log(personObject.getName());
//returns: John
var test = JSON.stringify(personObject);
var newPersonObject = JSON.parse(test);
console.log(newPersonObject);
//returns: Object
console.log(newPersonObject.getName());
//returns: Uncaught TypeError: Object #<Object> has no method 'getName'
};
为什么在JSON.stringify和JSON.parse之后此Person对象为空并且丢失所有方法的任何建议?
Any suggestions why this Person object after JSON.stringify and JSON.parse is empty and loses all it's methods?
推荐答案
函数不是有效的JSON数据类型。当然,函数保存的变量范围也无法序列化。
Functions are not a valid JSON data type. And certainly the variable scope held by the functions can't be serialized.
您需要将数据直接存储在对象上以进行序列化。
You need to store data directly on the object to serialize it.
JSON有对象(键/值对)和数组(有序列表)样式结构,以及 string
, number
, true
, false
, null
。
JSON has "object" (key/value pair) and "array" (ordered list) style structures, as well as string
, number
, true
, false
, and null
.
这篇关于如何在不获取空对象的情况下使用JSON.stringify和JSON.parse?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!