小编典典

JavaScript序列化和方法

json

我是“面向对象” JavaScript的新手。当前,我有一个需要跨页面传递的对象。我的对象定义如下:

function MyObject() { this.init(); }
MyObject.prototype = {
    property1: "",
    property2: "",

    init: function () {
        this.property1 = "First";
        this.property2 = "Second";
    },

    test: function() {
      alert("Executing test!");
    }
}

在应用程序的第1页上,我正在创建MyObject的实例。然后,我将对象序列化并将其存储在本地存储中。我正在这样做,如下所示:

var mo = new MyObject();
mo.test();                                    // This works
window.localStorage.setItem("myObject", JSON.stringify(mo));

现在,在第2页上,我需要获取该对象并使用它。要检索它,我使用以下方法:

var mo = window.localStorage.getItem("myObject");
mo = JSON.parse(mo);
alert(mo.property1);    // This shows "First" as expected.
mo.test();              // This does not work. In fact, I get a "TypeError"  that says "undefined method" in the consol window.

基于输出,看起来就像当我序列化对象时,某种程度上函数被丢弃了。我仍然可以看到属性。但是我无法与任何功能进行交互。我究竟做错了什么?


阅读 236

收藏
2020-07-27

共1个答案

小编典典

函数不能序列化为JSON对象。

因此,我建议您为实际属性创建一个单独的对象(或对象内的属性),然后序列化此部分。之后,您可以使用其所有功能实例化对象,并重新应用所有属性以重新获得对工作对象的访问权限。

按照您的示例,它可能看起来像这样:

function MyObject() { this.init(); }
MyObject.prototype = {
    data: {
      property1: "",
      property2: ""
    },

    init: function () {
        this.property1 = "First";
        this.property2 = "Second";
    },

    test: function() {
      alert("Executing test!");
    },


   save: function( id ) {
     window.localStorage.setItem( id, JSON.stringify(this.data));
   },
   load: function( id ) {
     this.data = JSON.parse( window.getItem( id ) );
   }

}
2020-07-27