0

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.

Kosmo零
  • 4,001
  • 9
  • 45
  • 88
  • 1
    eval is not bad at all, you can't parse a script without it. it's doing stupid crap with eval that's the problem. if your site has no user-generated unmoderated input, then eval is without risk. at any rate, Function() is no better, and in fact, eval() can be made safe in "use strict", but "Function" cannot. – dandavis Jul 18 '14 at 18:56

1 Answers1

2

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 ;)

Community
  • 1
  • 1
Boyan Hristov
  • 1,067
  • 3
  • 15
  • 41
  • +1 Never knew this! Is there any big difference between this and `eval` other than the fact that this can be called multiple times? – Casey Falk Jul 18 '14 at 18:16
  • 1
    To me it looks like you are just creating a function using the function constructor, so it should be much faster than eval (not sure) – Boyan Hristov Jul 18 '14 at 18:17