SPlatten
SPlatten

Reputation: 5762

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.

Upvotes: 1

Views: 54

Answers (2)

user663031
user663031

Reputation:

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.

Upvotes: 0

Oriol
Oriol

Reputation: 288710

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

Upvotes: 3

Related Questions