Я встраиваю Rhino в приложение Java. По сути, я запускаю код Javascript, который затем вызывает функцию Java, а это вызывает другой код Javascript. При запуске второго кода Javascript у меня возникают проблемы, потому что общая область, которую я использую, не может видеть объекты в новой области.
Вот тест, который показывает ошибку (обратите внимание, что у меня есть две общие области для воспроизведения того же сценария, что и в приложении):
import org.junit.Test;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
public class SimpleRhinoTest {
static class DynamicScopeFactory extends ContextFactory {
@Override
protected boolean hasFeature(Context cx, int featureIndex) {
if (featureIndex == Context.FEATURE_DYNAMIC_SCOPE) {
return true;
}
return super.hasFeature(cx, featureIndex);
}
}
static {
ContextFactory.initGlobal(new DynamicScopeFactory());
}
public static class HelperScope extends ScriptableObject {
private ScriptableObject sharedScope;
@Override
public String getClassName() {
return "global";
}
public void debug(String text) {
System.out.println(text);
}
public void doSomething1(String param) {
debug(param);
Context ctx = Context.enter();
Scriptable scriptScope = ctx.newObject(sharedScope);
scriptScope.setPrototype(sharedScope);
scriptScope.setParentScope(null);
ctx.evaluateString(scriptScope, "var currentScope = 'test2';", "", 1, null);
ctx.evaluateString(scriptScope, "foo(); doSomething2('end')", "", 1, null);
Context.exit();
}
public void doSomething2(String param) {
debug(param);
}
public ScriptableObject getSharedScope() {
return sharedScope;
}
public void setSharedScope(ScriptableObject sharedScope) {
this.sharedScope = sharedScope;
}
}
@Test
public void testSharedScopes() {
// init shared scopes
Context ctx = Context.enter();
HelperScope helperScope1 = new HelperScope();
ScriptableObject sharedScope1 = ctx.initStandardObjects(helperScope1, true);
String[] names = {"doSomething1", "doSomething2", "debug"};
helperScope1.defineFunctionProperties(names, HelperScope.class, ScriptableObject.DONTENUM);
ctx.evaluateString(sharedScope1, "var foo = function() { debug(currentScope); };", "", 1, null);
sharedScope1.sealObject();
Context.exit();
ctx = Context.enter();
HelperScope helperScope2 = new HelperScope();
ScriptableObject sharedScope2 = ctx.initStandardObjects(helperScope2, true);
names = new String[] {"doSomething1", "doSomething2", "debug"};
helperScope2.defineFunctionProperties(names, HelperScope.class, ScriptableObject.DONTENUM);
ctx.evaluateString(sharedScope2, "var foo = function() { debug(currentScope); };", "", 1, null);
sharedScope1.sealObject();
Context.exit();
helperScope1.setSharedScope(helperScope2);
ctx = Context.enter();
Scriptable scriptScope1 = ctx.newObject(sharedScope1);
scriptScope1.setPrototype(sharedScope1);
scriptScope1.setParentScope(null);
ctx.evaluateString(scriptScope1, "var currentScope = 'test1'; foo(); doSomething1('entering');", "", 1, null);
Context.exit();
}
}
При запуске этого теста вы получите следующую ошибку:
org.mozilla.javascript.EcmaError: ReferenceError: "currentScope" is not defined. (#1)
Итак, я использую динамические закрытые прицелы, как описано здесь:
https://developer.mozilla.org/en-US/docs/Rhino/Scopes_and_Contexts
Что странно для меня, так это то, что в первый раз, когда я запускаю первый код Javascript, я могу без проблем получить доступ к переменной «currentScope». Исключение выдается при втором выполнении скрипта, хотя я использую тот же код для инициализации второй области видимости.
Что я делаю не так?
Спасибо!