本文介绍了为什么对定义函数的字符串的求值返回的是undefined而不是函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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
是一个函数.
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?
推荐答案
您需要生成一个表达式.
You need an expression to be produced.
更改
var fct1 = eval(fctStr);
到
var fct1 = eval("("+fctStr+")");
这篇关于为什么对定义函数的字符串的求值返回的是undefined而不是函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!