Hi
I am using rhino for running a script file for me and I got sth. that
really pazzles me.
What I want is to create a clean js scope, context.initStandardObjects
is also OK but it costs too much memory. Is there any new way?
java class:
package com.hurry07.engine;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
public class ScopeTest {
static Context context = null;
static Scriptable scope = null;
public static void main(String[] args) {
Context context = Context.enter();
ScriptableObject global = context.initStandardObjects(null,
true);
Scriptable scope = context.newObject(global);
ScopeTest.context = context;
ScopeTest.scope = scope;
System.out.println("=================");
execute(new File("resource/engine/scopetest.js"));
scope = context.newObject(global);
ScopeTest.context = context;
ScopeTest.scope = scope;
System.out.println("=================");
execute(new File("resource/engine/scopetest.js"));
Context.exit();
}
public static void execute(File file) {
if (file == null || !file.exists()) {
return;
}
Reader r = null;
try {
r = new InputStreamReader(new FileInputStream(file),
"UTF-8");
} catch (FileNotFoundException e) {
e.printStackTrace(System.out);
} catch (UnsupportedEncodingException e) {
e.printStackTrace(System.out);
}
if (r == null) {
return;
}
try {
context.evaluateReader(scope, r, "", 1, null);
r.close();
} catch (Throwable e) {
e.printStackTrace(System.out);
}
}
}
and here is script file, and it located under a relative path
'resource/engine':
function alert(o) {
if (o) {
java.lang.System.out.println(o.toString());
}
}
if (typeof vara == 'undefined') {
vara = 'aaa'; // there is no key word 'var' !, the only different.
alert('create new vara:' + vara);
} else {
alert('vara exists:' + vara);
}
if (typeof varb == 'undefined') {
var varb = 'bbb';
alert('create new varb:' + varb);
} else {
alert('varb exists:' + varb);
}
after running this file twice, I got:
=================
create new vara:aaa
create new varb:bbb
=================
vara exists:aaa
create new varb:bbb
what I expect is:
=================
create new vara:aaa
create new varb:bbb
=================
create new vara:aaa // <---------- here is different
create new varb:bbb
_______________________________________________
dev-tech-js-engine-rhino mailing list
[email protected]
https://lists.mozilla.org/listinfo/dev-tech-js-engine-rhino