te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>json - JavaScript Serialization and Methods - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

json - JavaScript Serialization and Methods - Stack Overflow

programmeradmin4浏览0评论

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

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

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?

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

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

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?

Share Improve this question edited Mar 12, 2012 at 14:00 Henrik Hansen 2,1901 gold badge14 silver badges19 bronze badges asked Mar 12, 2012 at 13:54 user208662user208662 11k27 gold badges76 silver badges86 bronze badges
Add a ment  | 

7 Answers 7

Reset to default 7

JSON doesn't serialize functions.

Take a look at the second paragraph here.

If you need to preserve such values, you can transform values as they are serialized, or prior to deserialization, to enable JSON to represent additional data types.

In other words, if you really want to JSONify the functions, you can convert them to strings before serializing:

mo.init = ''+mo.init;
mo.test = ''+mo.test;

And after deserializing, convert them back to functions.

mo.init = eval(mo.init);
mo.test = eval(mo.test);

However, there should be no reason to do that. Instead, you can have your MyObject constructor accept a simple object (as would result from parsing the JSON string) and copy the object's properties to itself.

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

}

To avoid changing the structure, I prefer to use Object.assign method on object retrieval. This method merge second parameter object in the first one. To get object methods, we just need an empty new object which is used as the target parameter.

var mo = window.localStorage.getItem("myObject");
// this object has properties only
mo = JSON.parse(mo);
// this object will have properties and functions
var pleteObject = Object.assign(new MyObject(), mo);

Note that the first parameter of Object.assign is modified AND returned by the function.

it looks like when I serialized the object, somehow the functions get dropped... What am I doing wrong?

Yes, functions will get dropped when using JSON.stringify() and JSON.parse(), and there is nothing wrong in your code.

To retain functions during serialization and deserialization, I've made an npm module named esserializer to solve this problem -- the JavaScript class instance values would be saved during serialization on Page 1, in plain JSON format, together with its class name information:

var ESSerializer = require('esserializer');

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

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

    test: function() {
      alert("Executing test!");
    }
}
MyObject.prototype.constructor=MyObject; // This line of code is necessary, as the prototype of MyObject has been overridden above.

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

Later on, during the deserialization stage on Page 2, esserializer can recursively deserialize object instance, with all types/functions information retained:

var mo = window.localStorage.getItem("myObject");
mo = ESSerializer.deserialize(mo, [MyObject]);
alert(mo.property1);    // This shows "First" as expected.
mo.test();              // This works too.

That's because JSON.stringify() doesn't serialize functions i think.

You're right, functions get dropped. This page might help:

http://www.json/js.html

"Values that do not have a representation in JSON (such as functions and undefined) are excluded."

Serializing methods is not a standard and can use a lot of place.

Here an alternative, to recover an object serialized with JSON.stringify :

function recoverObject (target, source) {
  for (const key of Object.getOwnPropertyNames(source)) {
    const value = source[key]
    if (value === Object(value)) {
      target[key] = classInstanceByName(key)
      recoverObject(target[key], value)
    } else {
      target[key] = value
    }
  }
}

And bellow there is an example of classInstanceByName

function classInstanceByName (key) {
  const map = {
    attacks: [],
    bag: new Bag(),
    currentPlace: new Place(),
    currentScenario: new Scenario({}),
    fight: new Fight(),
    nextScenario: new Scenario({})
  }
  return map[key] || new Object()
}

There is two downside :

  • All your variables that share the same name must have the same class
  • You must have patible constructor for each class
发布评论

评论列表(0)

  1. 暂无评论