Detect if Javascript function exists before trying to call it

Jul 24, 2011 at 11:02 PM

 

I'm setting up a structured Javascript file where certain functions must exist and others will get called if they're defined.   For example, I would like to have a main() function which is always the entry point into invoking the script.   That's easy enough to do with CallFunction().   However, how do I ensure the function exists before calling it?   Because if it doesn't, then that is an error and I would want to flag that in the very beginning just after the script file was initially loaded by my C# code 

In the second part of that question, I want to have well-known callback function names on the Javascript side.   The C# side will call these functions at the appropriate time if they're there.   That's the problem I'm having again.   How do I know if they're "there" in the first place to call?  

What I don't want to do is to look at the raw code I pull in as a string and search it with regular expressions.  After all, the interpreter has already parsed that source string and knows everything about what's in it.   I just need to get at what the interpreter already knows in this regard.

Thanks for the help.

Coordinator
Jul 25, 2011 at 12:06 AM

There are two solutions:

First you could compile the script by calling JintEngine.Compile, and get a Program instance which contains object representing the script. If there is one of type FunctionDeclaration with the identifier you want, there it is. Once you get this Program instance, you can even run it directly using engine.Run()

Otherwise you can run your script, then call engine.Run("return main;") which will either return an object of type JsFunction or null if the function "main()" is undefined.


Jul 25, 2011 at 7:56 AM
Here's the 2 solutions.   Count will be 1 if "main" exists in the 1st solution.  The 2nd solution is a better code read where the variable main will be null if "main" doesn't exist.
var source = File.ReadAllText("file.js");
var program = JintEngine.Compile(source, false);
var jint = new JintEngine();
jint.Run(program);

var count = (from x in
                   from y in program.Statements
                          where y.GetType() == typeof(FunctionDeclarationStatement)
                          select (FunctionDeclarationStatement) y
             where x.Name == "main"
             select x).ToList().Count;
            
var main = jint.Run("return main;");