anonymous
anonymous

Reputation:

executing anonymous functions created using JavaScript eval()

I have a function and its contents as a string.

var funcStr = "function() { alert('hello'); }";

Now, I do an eval() to actually get that function in a variable.

var func = eval(funcStr);

If I remember correctly, in Chrome and Opera, simply calling

func();

invoked that function and the alert was displayed.

But, in other browsers it wasn't the case. nothing happened.

I don't want an arguement about which is the correct method, but how can I do this? I want to be able to call variable(); to execute the function stored in that variable.

Upvotes: 20

Views: 21771

Answers (11)

gogog
gogog

Reputation: 420

This is also ok.

var func = eval("_="+funcStr);

Upvotes: 1

gx0r
gx0r

Reputation: 5471

function-serialization-tools provides a function, s2f(), that takes a string representation of a function and returns it as a function.

Upvotes: -1

A. Wheatman
A. Wheatman

Reputation: 6386

We solved this problem by preparing universal function parser that convert string to real JavaScript function:

if (typeof String.prototype.parseFunction != 'function') {
    String.prototype.parseFunction = function () {
        var funcReg = /function *\(([^()]*)\)[ \n\t]*{(.*)}/gmi;
        var match = funcReg.exec(this.replace(/\n/g, ' '));

        if(match) {
            return new Function(match[1].split(','), match[2]);
        }

        return null;
    };
}

examples of usage:

var func = 'function (a, b) { return a + b; }'.parseFunction();
alert(func(3,4));

func = 'function (a, b) { alert("Hello from function initiated from string!"); }'.parseFunction();
func();

here is jsfiddle

Upvotes: 4

candieduniverse
candieduniverse

Reputation: 16166

A simple example of defining a function as a string, eval()ing it, and passing in a parameter while immediately invoking the function (and then dumping the result to the console):

console.log('eval: %s', eval("(function(foo) { return foo.bar; })")({"bar": "12345"}));

This produces output like the following.

eval: 12345

Upvotes: 0

Ferdinand Liu
Ferdinand Liu

Reputation: 334

EVAL without eval()...

function evalEx(code){
  var result,D=document,S=D.createElement('script'),
  H=D.head||D.getElementsByTagName['head'][0],
  param=Array.prototype.slice.call(arguments);
  code='function evalWE(){'+code+'}';
  S.innerText===''?S.innerText=code:S.textContent=code;
  H.appendChild(S);
  result=evalWE.apply(this,param);
  H.removeChild(S);
  return result
}

Usage Example:

ABC=evalEx('return "ABC"');
nine=evalEx('return arguments[1]+arguments[2]',4,5);

Upvotes: 0

user319862
user319862

Reputation: 1857

I realize this is old, but it was the only valid result coming up in my google searches for evaluating anonymous javascript function strings.

I finally figured out how to do it from a post on the jquery google group.

eval("false||"+data)

where data is your function string like "function() { return 123; }"

So far, I have only tried this in IE8 and FF8 (the browsers on my personal computer), but I believe jquery uses this internally so it should work just about everywhere.

Upvotes: 8

Zoidberg
Zoidberg

Reputation: 10333

What also works is

var myFunc = function(myParam){
   // function body here
}

Upvotes: -1

SLaks
SLaks

Reputation: 887767

IE cannot eval functions (Presumably for security reasons).

The best workaround is to put the function in an array, like this:

var func = eval('[' + funcStr + ']')[0];

Upvotes: 15

Blixt
Blixt

Reputation: 50179

How about this?

var func = new Function('alert("hello");');

To add arguments to the function:

var func = new Function('what', 'alert("hello " + what);');
func('world'); // hello world

Do note that functions are objects and can be assigned to any variable as they are:

var func = function () { alert('hello'); };
var otherFunc = func;
func = 'funky!';

function executeSomething(something) {
    something();
}
executeSomething(otherFunc); // Alerts 'hello'

Upvotes: 34

David Henderson
David Henderson

Reputation: 1175

Try

var funcStr = "var func = function() { alert('hello'); }";

eval(funcStr);

func();

Upvotes: 6

Andreas Grech
Andreas Grech

Reputation: 107990

Use the eval like this :

var func = eval('(' + funcStr + ')');

Upvotes: 4

Related Questions