It the context of a one-page application development, I need to transform a string into an executable function.
var repo = {};
I used strings in 2 formats :
repo.toto = "function toto(){\
alert('Hello, I am toto');\
}";
repo.titi = "function titi(){\
this.sub1 = function() {};\
this.sub2 = function() {};\
this.sub3 = function() {};\
}";
I want to know if a function once executed will give, or not, an object of sub-functions.
Below is a full case that illustrate my problem. Eval
is not a solution.
var createFunc = function(name) {
var string = repo[name];
var func = Function("return new "+string+"");
repo[name] = func;
};
typeof repo.toto; //string
typeof repo.titi; //string
createFunc('toto');
createFunc('titi');
typeof repo.toto; //function
typeof repo.titi; //function
repo['toto'](); //alert('Hello, I am toto');
//Object {}
repo['titi']();
//Object { sub1: anonymous/titi/this.sub1(), sub2: anonymous/titi/this.sub2(), sub3: anonymous/titi/this.sub3() }
Do you know a way to determinate if the function will give an empty object (like in the "toto" example) or not (like the "titi" example), without having to execute the function?