gpt4 book ai didi

javascript - 为什么对定义函数的字符串求值会返回 undefined 而不是函数?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:34:01 24 4
gpt4 key购买 nike

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+")");

关于javascript - 为什么对定义函数的字符串求值会返回 undefined 而不是函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27508784/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com