Yes I know eval is evil but …
Few times I saw a function being created from a string in few different ways:
var s = "function fname() { this.m = function(s){alert(s);}}";
//1
var x = new( eval("("+s+")") );
x.m("aaa")
//2
var x = new( eval('[' + s + ']')[0] );
x.m("bbb")
//3
var x = new ( eval(s + " fname;") );
x.m("ccc")
The first 2 are clear to me but I wonder about the third one.
Could someone explain how adding a name of the function after it’s definition helps eval do the job ?
Also do you know any other ways of using eval to create funcions ?
Thanks
Szymon
First, with the
functiondeclaration (which is not an expression), you create the function and put it into the current scope:The closing brace finishes the function statement, and an expression follows:
As the function is already in the scope, the expression
fnamesimply refers to the function. And because the expression is the last thing in your eval’ed code,evalreturns exactly that function reference.Instead of
fname, you could write the name of any function in the current scope, e.g.alert, which would then be returned byeval.