简体   繁体   中英

TypeError: Cannot find function blah in

I'm using the JavaScript support in javax.script to do some basic unit testing of JS scripts and I've run into a problem.

I have some code that eval(...) s the pre-requisite lib files I have in an instance of ScriptEngine, including the one that has my function blah in it.

I then eval a further file in the same instance of ScriptEngine, in which I have some functions that serve as tests, and then I invoke the tests.

However, despite all the evals working without issue, I get an error that to me suggests a problem loading the function.

javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: TypeError: Cannot find function blah. (<Unknown source>#x) in <Unknown source> at line number x

Two separate eval calls on the same ScriptEngine works for me. Are you setting a new ScriptContext or otherwise eliminating your definition of blah ?

public class TryScripting {
    public static void main(String[] args) throws ScriptException {
    ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
    String makeFun = "function  hello() {\n" +
            "return \"hello world\";\n" +
            "}\n" +
            "{\n" +
            "}";
    engine.eval(makeFun);

    engine.eval("myVar = hello()");
    ret = engine.get("myVar");
    System.out.println(ret);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM