简体   繁体   中英

How to call a function defined as a string?

I want to define functions and scripts in a database record then using Javascript convert the database field from a string to code.

I was thinking I could use 'eval', but this doesn't seem to work.

As an example:

    var strTest = "function(strParams) { alert('hello: ' + strParams); };"
       ,fn = eval(strTest);
    fn("World");

This doesn't work, eval returns undefined, hopefully this gives the idea of what I am trying to achieve.

The problem is that eval parses your function as a function declaration. But function declarations require a name.

Instead, you should make it a function expression, which doesn't require one.

var strTest = "(function(strParams) { alert('hello: ' + strParams); })";
eval(strTest)("World");

Only do this if you trust the string.

Alternatively, you may be interested in the Function constructor:

var f = Function("strParams", "alert('hello: ' + strParams)");
f("World");

You could try something like this:

<script src="http://my-server/js-func/foobar.js"></script>

and have the server serve up the JS retrieved from the DB at that endpoint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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