I working with jQuery and i needed to generate an anonymous method with the eval() function.
The following lines worked with Opera but not with IE, FF, Chrome:
var callbackStr = "function(){alert('asdf');}";
var callback = eval(callbackStr);
callback();
This code works with all Browsers:
var callbackStr = "var callback = function(){alert('asdf');}";
eval(callbackStr);
callback();
You see, I already solved my problem. But I want to know, what exactly is happening. Can anybody explain this behaviour to me, or tell me where i can find further information?
(PS: I know this page.)
The reason is the same as the reason you need to wrap parentheses around JSON strings before using eval
on them - eval treats eval assumes the anonymous functions is a FunctionDeclaration. Using parentheses allows eval to treat what's inside as an expression:{
as a token, the start of a statement
var callbackStr = "(function(){alert('asdf');})";
var callback = eval(callbackStr);
callback();
// -> alerts 'asdf';
As for why Opera behaves differently here, I have no idea. As for your use of eval
, there's probably a better way (there nearly always is).
I dug out a quote from the spec for you, section 12.4 of ECMA-262 3rd Edition:
Note that an ExpressionStatement cannot start with an opening curly brace because that might make it ambiguous with a Block. Also, an ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.
Emphasis mine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With