相当于Ruby在Javascript中的“需求”

时间:2010-10-22 16:36:54

标签: javascript rhino

如何在Javascript中“请求”另一个文件到现有文件中?是否有类似于Ruby的“require”或“load”?

>注意:我在服务器(Rhino)中使用JS

原因:我只需要访问其他JS文件中的方法。

更新:从cmd行执行时,。当我尝试以编程方式调用它时,它失败了。这是我的代码:http://pastie.org/1240495

2 个答案:

答案 0 :(得分:3)

要在Java中嵌入的js中使用加载函数,必须首先在脚本上下文中公开它。可能有一种方法可以从Java中完成,但你也可以使用js来完成它。

免责声明:此解决方案使用源自我一直在处理的Apache许可项目的源代码。您可以看到原始源文件here

此js文件设置全局变量,并存在于名为setupglobals.js的文件中:

var shell = org.mozilla.javascript.tools.shell.Main;
var args = ["-e","var a='STRING';"];
shell.exec(args);

var shellGlobal = shell.global;

//grab functions from shell global and place in current global
load=shellGlobal.load;
print=shellGlobal.print;
defineClass=shellGlobal.defineClass;
deserialize=shellGlobal.deserialize;
doctest=shellGlobal.doctest;
gc=shellGlobal.gc;
help=shellGlobal.help;
loadClass=shellGlobal.loadClass;
quit=shellGlobal.quit;
readFile=shellGlobal.readFile;
readUrl=shellGlobal.readUrl;
runCommand=shellGlobal.runCommand;
seal=shellGlobal.seal;
serialize=shellGlobal.serialize;
spawn=shellGlobal.spawn;
sync=shellGlobal.sync;
toint32=shellGlobal.toint32;
version=shellGlobal.version;
environment=shellGlobal.environment;

这是您的原始Java主机文件,现在已经过扩充,可以在任何其他脚本之前评估setupglobals.js:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import org.mozilla.javascript.*;

public class RhinoRunner {
    public static void main(String args[]) throws IOException 
    {
        BufferedReader script = new BufferedReader(new FileReader("setupglobals.js"));
        BufferedReader script2 = new BufferedReader(new FileReader("example.js"));
        Context context = Context.enter();
        try {
            ScriptableObject scope = context.initStandardObjects();
            context.evaluateReader(scope, script, "script", 1, null);
            context.evaluateReader(scope, script2, "script2", 1, null);
            Function fct = (Function)scope.get("abc", scope);
            Object result = fct.call(context, scope, scope, new Object[] {2, 3});
            System.out.println(Context.jsToJava(result, int.class));
        } 
        finally 
        {
            Context.exit();
        }
    }
}

这是你的example.js,现在扩充为使用全局加载函数加载文件hello.js:

function abc(x,y) 
{
    return x+y 
}

load("hello.js")

最后,这是hello.js:

print("hello world!")

执行时,RhinoRunner会打印以下内容:

hello world!
5

答案 1 :(得分:2)

在Rhino shell中,您可以使用load(),这是一种预定义的全局方法:

  

<强> load([filename, ...])

  加载由字符串参数命名的JavaScript源文件。如果给出了多个参数,则会读入并依次执行每个文件。

相关问题