Search code examples
javascriptstringexecute

How to execute function calls that passed in JS function as string without eval?


I think this is kind of unusual, but this is what I came to. I have a .net application that generates html + js page. I have a thing called Unit that is kind of assembly of different html elements and has artificial events onlaod and onunload.

function DisplayableUnit(content, onload_js, onunload_js)
{
    this.onload_js = onload_js; //different functions calls like "f1(); f2();"
    this.onunload_js = onunload_js;
    this.content = content; //string of html tags
}

function loadUnitTo(elem_id, unit)
{
    var elem = document.getElementById(elem_id);

    if (elem)
        elem.innerHTML = unit.content;

    if (unit.onload_js)
        ;//how to execute it?
}

Many sites says that eval is bad and unsafe thing. But is that the only choice? I need pure JS solution without any third party things.


Solution

  • You can execute it as a function like this:

    var theInstructions = "alert('Hello World'); var x = 100",
        F=new Function (theInstructions);
    
    return(F());
    

    Copied from this stackoverflow thread ;)