从eval中获取函数列表

Get list of functions from eval

本文关键字:函数 列表 获取 eval      更新时间:2023-09-26

背景

我有一个在WSH下运行的JScript脚本。

在我的代码中,我使用eval()函数。传递给eval()的字符串本质上是要执行的另一段代码。我期望这个代码定义一个特定名称的函数。比如func()

问题

我如何知道预期定义的函数是否确实存在,并且在eval()调用后可以调用。

努力1-失败

function isFuncCallable() {
    for (var m in this)
        if (typeof this[m] == "function" && this[m] == 'func')
            return true;
    return false;
}
eval("function func() { WScript.Echo('"func was called'") }");
if (isFuncCallable())
    func();
else
    WScript.Echo("func is not callable");

isFuncCallable不能像我预期的那样工作。它返回false,但如果我调用func(),它将是一个有效的调用。


更新1

如建议

这适用于

function isFuncCallable() {
    for (var m in this)
        if (typeof  this[m] == "function" && m == 'func')
            return true;
    return false;
}
eval("function func() { WScript.Echo('"func was called'") }");
if (isFuncCallable())
    func();
else
    WScript.Echo("func is not callable");
}

而这不是:

function Main() {
    function isFuncCallable() {
        for (var m in this)
            if (typeof this[m] == "function" && m == 'func')
                return true;
        return false;
    }
    eval("function func() { WScript.Echo('"func was called'") }");
    if (isFuncCallable())
        func();
    else
        WScript.Echo("func is not callable");
}
Main();

您不需要使用this[m]

if (typeof this[m] == "function" && this[m] == 'func')

应该是

if (typeof this[m] == "function" && m == 'func')

相反,因为for (x in y)迭代y的每个元素,所以您正在考虑使用for (x = 0; x < y.length; x++)风格的语法。

我知道这个问题很老,但这里有一个解决方案供参考:

// b.js
// use IIFE to return an object with all exported functions and data
(function() {
    return {
       sum: function(a, b) { return a + b; }
    };
})();

现在在另一个文件中

var fso = new ActiveXObject("Scripting.FileSystemObject");
var b = eval(fso.OpenTextFile('b.js',1).ReadAll());
WScript.Echo(b.sum(3, 4));
for(var p in b)
{
    WScript.Echo(p);
}
// the output should be
// 7
// sum