当我运行此 java 代码时,我能够获取函数外部定义的变量值,但无法获取函数内部定义的变量值。如何访问这些变量值?
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;
public class JSFunctionTest {
public static void main(String args[]) {
String code = "var name='nc',global_a = 'jill'; " + "\n"+
"function myfunc(b) { " + "\n"+
"var local_a = 1;" + "\n"+
"global_a = 'jack';" + "\n"+
" return b;" + "\n"+
"}";
Context context = Context.enter();
context.setGeneratingDebug(true);
context.setOptimizationLevel(-1);
Scriptable scope = context.initStandardObjects();
context.evaluateString(scope, code, "code", 1, null);
//getting values of varables
System.out.println("var name:"+scope.get("name", scope));
System.out.println("var global_a:"+scope.get("global_a", scope));
System.out.println("var local_a:"+scope.get("local_a", scope));//not found becase function wasnt run
//calling the function.
Object fObj = scope.get("myfunc", scope);
if (!(fObj instanceof Function)) {
System.out.println("myfunc is undefined or not a function.");
} else {
Object functionArgs[] = { "nc" };
Function f = (Function)fObj;
Object r = f.call(context, scope, scope, functionArgs);
String report = "myfunc('nc') = " + Context.toString(r);
//trying to access global and local a after calling function
System.out.println("var global_a:"+scope.get("global_a", scope));//values is changed, because this is defined out side the function.
System.out.println("var local_a:"+scope.get("local_a", scope));// still not found,after running the function.
System.out.println(report);
}
}
}