Hernan
Hernan

Reputation: 6063

Javascript anonymous functions in Firefox 7

After updating to Firefox 7, I am getting the following error:

function statement requires a name

This particular functions is defined as

fun = eval("function (item) { //Function body }");

If I rewrite it as:

fun = eval("function view(item) { //Function body }");

The error does not show up any more, but the program still does not work.

Ps.- I know that evaluating a string is not a good idea. This is a legacy application that I have to fix in which some functions are downloaded from a database as strings on demand.

Upvotes: 2

Views: 1358

Answers (4)

b-dur
b-dur

Reputation: 1

if the function is defined as a string and you wish to use it without calling eval everytime, you could do this:

var myFunc = 'function(){alert("myFunc");}';    
var fun = eval('(function(){return '+myFunc+'})()');
fun();

Or just

var myFunc = 'function(){alert("myFunc");}';    
var fun = eval('('+myFunc+')');
fun();

Upvotes: 0

mateusz.fiolka
mateusz.fiolka

Reputation: 3100

just a guess, maybe try with:

fun = eval("return function (item) { //Function body }");

(I just added the return statement)

Upvotes: 0

jAndy
jAndy

Reputation: 236022

A function declaration (is what you've got there) requires an identifier by spec.

function() {
}

just like that is not allowed by ES specification (even if some browsers might allow it anyway). Only function expression may be anonymous.

Upvotes: 2

Petah
Petah

Reputation: 46040

Wrap it in brackets

eval("(function (item) { alert('hello'); })");

But that doesn't make sense as it does nothing. Maybe you want:

eval("(function () { alert('hello'); })()");

Or

eval("var func = function (item) { };");

Upvotes: 5

Related Questions