0

My problem is, that I can't access the methods of an object, after using JSON.stringify and JSON.parse.

I have something like the following:

main.js

    var items = [];

    define(['item'], function (item) {

    var main = function () {

    $(document).ready(function) {

    $("#anyButton").on("click", function() {
    items.push(new item());
    items[0].myMethod();    //items[0].myMethod() works fine here.
          });
        });
      }();
    });

item.js

    var item = function () {
        var construnctor,
            that = {};

        constructor = function () {
            return that;
        };

        that.myMethod= function () {
        };

      return constructor.apply(null, arguments);
    };
    return itemModule;

Now I want to stringify the items Array in main.js and store it to localStorage:

main.js

window.localStorage.setItem("myKey", JSON.stringify(items));

And then parse it back:

var parsedArray = [];
parsedArray = JSON.parse(window.localStorage.getItem("myKey"));

Now the problem is, that I don't have access to myMethod in item.js The following fails:

parsedArray[0].myMethod();

produces:

parsedArray[0].myMethod is not a function.

Where is the problem? Thanks for your help.

Sam Hanley
  • 4,707
  • 7
  • 35
  • 63
ReyamOki
  • 83
  • 2
  • 8

1 Answers1

0

JSON.stringify will only convert value type property, array and objects.

Functions will be omited.

Remy Grandin
  • 1,638
  • 1
  • 14
  • 34
  • Ok, I didn't know functions can't be stringified. There is no proper way for me to do this without stringify. What do you think about http://www.eslinstructor.net/jsonfn/ – ReyamOki May 28 '15 at 14:14