简体   繁体   English

如何在不带eval的情况下执行以字符串形式传递给JS函数的函数调用?

[英]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. 我有一个生成html + js页面的.net应用程序。 I have a thing called Unit that is kind of assembly of different html elements and has artificial events onlaod and onunload. 我有一个叫做Unit的东西,它是不同html元素的组合,并具有onlaod和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. 我需要没有任何第三方东西的纯JS解决方案。

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 ;) 从复制计算器线程;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM