0

So to begin with I create an array of functions using some test (like this : "alert("Hello")") and convert that text into an anonymous function using the Function(text) method. e.g.

someArray[0] = Function('alert("Hello")');

I can then run this function like so:

someArray[0]();

This works fine, however I need to be able store this array in local storage previously I have been using JSOn.Stringify to store the array however it seems that once I store the array and retrieve it from storage I can no longer run the function.

My question is how do I store the array of functions so that I can retrieve them and run them later?

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • Why are you converting strings to functions? Where are these strings coming from? Can you store those strings in your object in local storage, and then re-call `new Function` again when you get them back? I'd suggest though, making named functions and just saving its name in your object. – gen_Eric Jan 02 '14 at 16:20
  • According to the responses to [a similar StackOverflow question][1], JSON can't store functions. [1]: http://stackoverflow.com/questions/8328119/can-i-store-regexp-and-function-in-json –  Jan 02 '14 at 16:21
  • This is generally a bad idea, and can make security holes. – SLaks Jan 02 '14 at 16:23
  • What are you trying to achieve that has led you to store a function as a string? My naive suggestion is that you do not do this in such a manner if another approach could be found that did not leverage an approach with an inherent security risk. – mccainz Jan 02 '14 at 16:27
  • I'm writing an emulator in JavaScript in which you can design your own CPU this is the method in which you can create the instruction set for your CPU, as someone else mentioned I will just store them as strings and use eval at run time. As no personally identifiable information is stored at all security is no longer a concern. –  Jan 02 '14 at 16:46

2 Answers2

2

JSON does not know functions, your best guess would be storing an array of strings and when you want to use them pass them to a Function object as argument.

user3152069
  • 408
  • 3
  • 9
0

You could base64 encode the function as a string. Save it in a json file. Load the json file into your page/app. base64 decode.

Then eval() to register your new function.

//load json data from file
var jsonData = {};

//Create string representation of function
var s = "function " + atob(jsonData.func);

//"Register" the function
eval(s);

//Call the function
//'test' is the name of the function in jsonData.func
test();

OR

//load json data from file
var jsonData = {};

//create function from base64 decode
var fn = Function(atob(jsonData.func));

//test
fn();

**Of course the function would need to be formatted differently for each of those examples.

Is there a way to create a function from a string with javascript?

Community
  • 1
  • 1
TDave00
  • 274
  • 6
  • 18