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.
Chrome中的此代码将
fct1
作为undefined
。为什么?我期望fct1
是一个函数。为什么要问这个问题是因为:How to write function-y accepting parameter-fct_x which accesses var-a which is required to be defined in function-y?
最佳答案
您需要生成一个表达式。
更改
var fct1 = eval(fctStr);
至
var fct1 = eval("("+fctStr+")");