0

I have an object that is stored locally on my users PC, stringified with JSON. I noticed that when i parse it back the methods disappear. What is the most efficient way to augment an object with a method?

EDIT: Example:

var data = {
    user: {
        username: "Adam"
    }
    //function goes here
}

var myFunction = function(){/* code here*/}
Adam Salma
  • 1,746
  • 1
  • 11
  • 22

2 Answers2

2

You can just assign the function to a property of the object:

var data = {
    user: {
        username: "Adam"
    }
    //function goes here
}

var myFunction = function(){/* code here*/}

data.myFunction = myFunction;
bhspencer
  • 13,086
  • 5
  • 35
  • 44
1

From my understanding of your problem, you can do like below.

var data = {
    user: {
        username: "Adam"
    },
    functionName : "myFunction"
}

var myFunction = function(){ alert("a"); }

var stringyJson = JSON.stringify(data);

var parsedJson = JSON.parse(stringyJson);

window[parsedJson.functionName]();

And if you want to pass arguments to function then add those in json and use like window[parsedJson.functionName](arg1, arg2);

sheilak
  • 5,833
  • 7
  • 34
  • 43
suyog patil
  • 412
  • 3
  • 13