2

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?

Guillaume Fe
  • 369
  • 4
  • 16
  • 4
    [That's impossible](https://en.wikipedia.org/wiki/Halting_problem). – Bergi Apr 25 '16 at 01:28
  • Btw, those functions you are constructing use [the `new function(){…}` antipattern](http://stackoverflow.com/q/10406552/1048572). `eval` does indeed seem more suitable here (you just have to call them with `new` later). – Bergi Apr 25 '16 at 01:31
  • Ok, so i guess I need to work on my design... Thank you to underline the halting problem – Guillaume Fe Apr 25 '16 at 01:52

1 Answers1

0

I will agree that it's not possible for every scenario.

But with the two sample inputs, the main difference is that one has properties and the other does not.

Note that with the return new you're instantiating the functions from the strings and returning the new instance. Any code directly inside the function will be executed (like a constructor) and the result will be an object of the properties and methods. So... that's why the first one returns an empty object.

You could tell if it will return an empty object or not if there isn't any this.(something)=. But it might not be the best solution, I don't see the use of this.

Gabriel
  • 2,170
  • 1
  • 17
  • 20
  • Thank you for your answer. When you said "You could tell", do you mean "with a regex"? – Guillaume Fe Apr 25 '16 at 02:02
  • It's possible with regex, yes. But remember that this is just an idea, it's not guaranteed to work for every case, my point was to explain what's happening with the code provided. – Gabriel Apr 25 '16 at 02:31