0

Total newbie question. how do i get the following code to work.

var f_str = "function test(msg) { alert(msg) }"
var f = eval(f_str)
f("hello")

The idea is to have the function test as a string, and be able to execute it as a function. eval doesn't seem to work, and i have tried JSON.parse too, without luck..

  • 3
    I don't know your actual need but if you're using eval, you're probably doing it wrong. – Grinn Dec 17 '12 at 15:12

2 Answers2

4

Add parentheses around f_str, so that it's interpreted as a function expression.

var f_str = "(function test(msg) { alert(msg) })";
var f = eval(f_str);
f("hello");

In your current code, the code is interpreted as a function declaration. You can see this by printing / using the value of test:

var f_str = "function test(msg) { alert(msg) }";
var f = eval(f_str);//^^^^
test("hello");   // <--
Rob W
  • 341,306
  • 83
  • 791
  • 678
0

This is usually a bad idea; if you want to execute dynamic JavaScript, you can use a snippet like this:

  (function() {
    var code = document.createElement('script');
    code.type = 'text/javascript';
    code.async = true;
    code.src = '/path/to/script';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(code, s);
  }());

Or use jQuery.getScript():

$.getScript('/path/to/script');
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309