在已解析的 Jint 程序中调用函数

Call a function in a parsed Jint program

我用Jint解析JS代码,调用里面的函数。当我使用多线程环境时,我使用程序解析方法,如对此问题的响应中所示:https://github.com/sebastienros/jint/issues/384

所以我有一个 Jint.Parser.Ast.Program 实例。我可以遍历其中的 IFunctionDeclaration 并找到我的函数。但我不知道如何实际调用函数...

Dim parser As New Jint.Parser.JavaScriptParser
Dim program As Jint.Parser.Ast.Program = parser.Parse(code)

For Each func As Jint.Parser.IFunctionDeclaration In program.FunctionDeclarations
    If func.Id.Name = myFunctionName Then
        ' How to call the function?
    End If
Next

我只找到了执行整个 Program 的方法。我假设我必须这样做,以便函数实际上是在引擎中定义的。但是,如何在我的脚本中调用某个函数?

一旦你的程序被执行,只需使用相同的方法来执行你的功能。示例是 c#

var parser = new Jint.Parser.JavaScriptParser();
// _parserCache is a static ConcurrentDictionary<string, Jint.Parser.Ast.Program>
var program = _parserCache.GetOrAdd(scriptName, key => parser.Parse(code));

foreach (var func in program.FunctionDeclarations)
{
    if (func.Id.Name == myFunctionName)
    {
        var exec = new Engine();
        // The entire program is executed, to define the function
        exec.Execute(program);
        // now you can call your function
        exec.Execute($"{myFunctionName}()");
    }
}