Skip to content Skip to sidebar Skip to footer

How To Convert Text To A Function Using Javascript

I have a text string that is correctly formatted as a function and I would like to convert it to an actual function. The text string looks like: function object_123(){ object_1

Solution 1:

Your string contains a function declaration.

When evaluated, it creates a object_123 variable in the scope of eval (which you can then call later) and returns nothing.

If you want to assign the function to this.func then you need to convert the declaration into a function expression. You can do that by wrapping it in parens.

this.func = eval("(" + func_txt ")" );

var func_txt = "function object_123(){\
   object_123_Action();\
   my_clicked(obj);\
}";

this.func = eval("(" + func_txt + ")");
var obj = "...";

functionobject_123_Action() {
  alert(1);
}

functionmy_clicked() {
  alert(2);
}


this.func();

Solution 2:

You can store your functions in an array on the object. Then, loop though the functions in another function and execute them.

var myObj = { 'myfunctions': [ ] };

and to add functions:

myObj.myFunctions.push (function () { /*function code here*/ });

Or if you already have a named function:

myObj.myFunctions.push (nameOfFunction);

And to call all the functions, use this function (don't add this function to myObj)

function executeMyFunctions (myObj) {
    for (var i = 0; i  < myObj.myFunctions.length; i++) {
        myObj.myFunctions[i]();
    }
}

And if it's possible to avoid using eval, you should.

Solution 3:

Try this:

functionparseStringToFunction(func) {
    func = func || '(function(){return null;})';
    return (newFunction('return ' + func)());
};

var stringifyFunction = '(function(a, b) { return a+b; })';

var callStringifyFunction = parseStringToFunction(stringifyFunction)(1, 2);
alert(callStringifyFunction); // results is 3

Also read this out: detail about eval() and new Function()

Solution 4:

Try this-

$("<script type='text/javascript'></script>").html(func_txt).insertAfter($("script"));

Solution 5:

This works:

assert( eval("(function(a, b) { return a+b; })")(1, 2) == 3 )

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#eval_as_a_string_defining_function_requires_(and)_as_prefix_and_suffix

Simply wrap the function in parens.

Post a Comment for "How To Convert Text To A Function Using Javascript"