I have an array of objects and each of these objects have a function, for example:
var array = [];
var object = {
param1: 0,
param2: 0,
function1: function(){
param1 += 1;
},
function2: function(){
param2 = new Date().getTime();
}
}
for(var i=0; i<5; i++){
array.push(object);
}
Then I want to convert this array to JSON and preserve the functions, so I do the following:
var json = JSON.stringify(array, function(key, val){
if(typeof(val) === "function"){
return val.toString();
}else{
return val;
}
});
Then I want to get the array with my objects back, so I do the following:
var newArray = JSON.parse(json);
But my problem starts here. The function that I saved in JSON variable were converted to strings, so I can't run it for example:
alert(newArray[0].param1); //It return 0
newArray[0].function1(); //It says "Uncaught TypeError: string is not a function"
alert(newArray[0].param1); //Do not show anything
How can I solve this? How can I run this function? I tried to use eval() without no success. I would like to solve it without jQuery or any plugins.