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.

1
  • 3
    you can't serialize functions into JSON - there is no such thing. Commented May 28, 2015 at 14:04

1 Answer 1

0

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

Functions will be omited.

Sign up to request clarification or add additional context in comments.

1 Comment

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 eslinstructor.net/jsonfn

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.