JavaScript序列化和方法 [英] JavaScript Serialization and Methods

查看:127
本文介绍了JavaScript序列化和方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to "object-oriented" JavaScript. Currently, I have an object that I need to pass across pages. My object is defined as follows:

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

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

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

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

On Page 1 of my application, I am creating an instance of MyObject. I am then serializing the object and storing it in local storage. I am doing this as shown here:

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

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

Now, on Page 2, I need get that object and work with it. To retrieve it, I am using the following:

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.

根据输出,看起来当我序列化对象时,某些功能会被丢弃。我仍然可以看到属性。但我不能与我的任何功能互动。我做错了什么?

Based on the outputs, it looks like when I serialized the object, somehow the functions get dropped. I can still see the properties. But I can't interact with any of my functions. What am I doing wrong?

推荐答案

无法将函数序列化为JSON对象。

Functions can not be serialized into a JSON object.

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

So I suggest you create a separate object (or property within the object) for the actual properties and just serialize this part. Afterwards you can instantiate your object with all its functions and reapply all properties to regain access to your working object.

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

Following your example, this may look like this:

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 ) );
   }

}

这篇关于JavaScript序列化和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆