我問這個問題的原因是因爲我想爲我的對象使用LocalStorage。正如你可能知道的,當使用LocalStorage時,你必須對JSON進行處理,然後將它們解析回javascript對象。如何JSON.stringify和JSON.parse沒有得到一個空的對象?
我想要JSON.stringify一個對象的方法,然後解析它,但我得到的是一個空對象。
請看看這段代碼。
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.js文件應該看起來不同於普通的對象屬性? – Axel 2013-05-11 02:14:23
@Axel:是的,如果您最終想要序列化數據,則數據需要直接在對象上,並且需要成爲JSON支持的有限數據子集的一部分。 – 2013-05-11 02:15:40