JavaScript (Rhino) use library or include other scripts

前端 未结 4 751
野趣味
野趣味 2020-12-24 06:44

In JDK6, is there a way to load multiple scripts, each in a file, and have the one script reference a method of another script? Sort of like \"include\"?

4条回答
  •  情深已故
    2020-12-24 07:08

    A real-life example this time, i.e. running the esprima parser with Rhino 1.7R4.

    import org.mozilla.javascript.Context;
    import org.mozilla.javascript.Scriptable;
    import org.mozilla.javascript.ScriptableObject;
    ...
    
    Context context = Context.enter();
    Scriptable globalScope = context.initStandardObjects();
    Reader esprimaLibReader = new InputStreamReader(getClass().getResourceAsStream("/esprima.js"));
    context.evaluateReader(globalScope, esprimaLibReader, "esprima.js", 1, null);
    
    // Add a global variable out that is a JavaScript reflection of the System.out variable:
    Object wrappedOut = Context.javaToJS(System.out, globalScope);
    ScriptableObject.putProperty(globalScope, "out", wrappedOut);
    
    String code = "var syntax = esprima.parse('42');" +
        "out.print(JSON.stringify(syntax, null, 2));";
    
    // The module esprima is available as a global object due to the same
    // scope object passed for evaluation:
    context.evaluateString(globalScope, code, "", 1, null);
    Context.exit();
    

    After running this code, you should see the output as follows:

    {
      "type": "Program",
      "body": [
        {
          "type": "ExpressionStatement",
          "expression": {
            "type": "Literal",
            "value": 42,
            "raw": "42"
          }
        }
      ]
    }
    

    So indeed, the trick is in reusing the globalScope object.

提交回复
热议问题