首先我要承认我是 JavaScript 菜鸟。因此,这个问题的基础知识可能不太完善,并且可能缺乏足够的信息来帮助我。
背景
我的组织有一个内部基于 Eclipse 的 JavaScript IDE。我们所要做的就是用 JavaScript 编写脚本并直接执行它们。我的猜测是它使用了 Rhino,因为我在一些异常的堆栈跟踪中看到了它。
我的代码运行在 3 个“.js”文件中。
Script-1:声明全局变量并将其实例化为 Java 对象
importClass(java.util.HashMap);
var hmTCResult = new HashMap();
Script-2:使用 Script-1 中的全局变量执行一些操作
Script-2.prototype.run = function() {
hmTCResult.put("Result", "Fail");
};
changeStatus = function(strStatus){
hmTCResult.put("Result", strStatus);
};
Script-3:调用 Script-2 中使用全局变量的函数
changeStatus("Pass")
问题定义
当我从 Script-3 调用 Script-2 中的函数时,它似乎没有选择实例变量,并且我的函数失败,即我收到异常“hmTCResult 未设置为对象的实例”。请注意,相同的变量 hmTCResult 在脚本 1 中运行良好。
我已经阅读了 JavaScript 中的作用域和上下文,但无法突破它,因为我没有在 IDE 中明确地看到它。
如果需要,我很乐意提供更多信息。
最佳答案
这很好用,只需调整你的范围并设置原型(prototype)搜索即可:
Context cx = Context.enter();
try {
// Cache and reuse:
ScriptableObject sealedSharedScope = cx.initStandardObjects(null,
true);
// Force the LiveConnect stuff to be loaded.
String loadMe = "RegExp; getClass; java; Packages; JavaAdapter;";
cx.evaluateString(sealedSharedScope, loadMe, "preLoadLazyLoad", 0,
null);
cx.evaluateString(sealedSharedScope, "varInRoot = 'blah';",
"setVarInRoot", 0, null);
// here you can put more cx.evaluateString calls to set up your
// environment (eg. hmTCResult)
// now connect a throw-away new scope into the hierarchy, with local
// vars:
Scriptable scope = cx.newObject(sealedSharedScope);
// ensure that definitions in the root scope are found
scope.setPrototype(sealedSharedScope);
// ensure that new global variables are created in this scope (don't
// use
// var for them!)
scope.setParentScope(null);
cx.evaluateString(scope, "localVar = varInRoot;", "mySource", 0,
null);
assertEquals("blah", scope.get("localVar", scope).toString());
// new var not in root:
assertEquals(ScriptableObject.NOT_FOUND,
sealedSharedScope.get("localVar", scope));
} finally {
Context.exit();
}
请注意,scope.get 不会搜索原型(prototype)链 - 必须自己执行此操作!
作用域独立于 Context 并且在 Context.exit() 后仍然存在。
关于java - 在 Rhino Javascript 中共享 java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12999095/