问题
function y(fct) {
var a = 2;
var fctStr = String(fct);
var fct1 = eval(fctStr);
console.log("fctStr=" + fctStr); // output: fctStr=function x() { return a + 1 }
console.log("fct1=");
console.log(fct1); // output: undefined. Why it is undefined? I expect fct1 is a function.
return fct1(); // exception: undefined is not a function.
}
function x() { return a + 1 }
y(x) // I expect it returns 3. However, it throws exception at above "return fct1()" statement.
This code in Chrome will get fct1
as undefined
. Why? I expected that fct1
would be a function.
Why this question is asked is because of this: How to write function-y accepting parameter-fct_x which accesses var-a which is required to be defined in function-y?
回答1:
You need an expression to be produced.
Change
var fct1 = eval(fctStr);
to
var fct1 = eval("("+fctStr+")");
回答2:
Other's have answered in bits an pieces, but here's the whole answer:
function x() {return a + 1}
That defines a function named x
, this is very similar to the following:
var x = function() {return a + 1}
In that case, an anonymous function is created and assigned to the variable x
. So if you want to assign a function to a variable, there shouldn't be an identifier between function
and ()
.
If you want the eval
statement to return the function, then you need to wrap the function declaration with parenthesis (and not give the function a name). Edit: The function name is optional:
var x = eval('(function () {return a + 1})');
来源:https://stackoverflow.com/questions/27508784/why-does-the-evaluation-of-a-string-defining-a-function-return-undefined-instead