The life cycle of a javascript variable in a java method

I am using javax.script to run javascript from a java method.

In my java method, I call different functions defined in javascript. On the javascript side, I want to keep the global variable, so the output of the call depends on the previous ones.

java method

public void myMethod(){ ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); engine.eval(new java.io.FileReader("myTest.js")); Invocable inv = (Invocable) engine; Object obj = engine.get("obj"); inv.invokeMethod(obj, "method1"); inv.invokeMethod(obj, "method2"); } 

myTest.js

 var obj=new Object(); var myStatus=1; obj.method1 = function(){ myStatus++; }; obj.method2 = function(){ for (var i=0; i<myStatus) println('Hello world'); } 

What is the scope of the variable declared in the script? If I add a global variable to the script using

 engine.put("globalVariable", myVariable) 

What is the scope of this variable?

thanks

+4
source share
1 answer
 engine.put("globalVariable", myVariable) 

To measure that this variable belongs to the engine, each script engine works with this variable, here is an example:

 ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); engine.put("status",0); engine.eval("status++; println(status);"); //print 1 engine.eval("status++; println(status);"); //print 2 

If you want to pass some script area parameters to you script, you should use bindings

 ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); Bindings bindings=engine.createBindings(); bindings.put("status",0); Bindings bindings2=engine.createBindings(); bindings2.put("status",0); engine.eval("status++; println(status);",bindings); //print 1 engine.eval("status++; println(status);",bindings2); //print 1 

Further, the variable defined in the script, if you do not use bindings, all of them are the scope of the engine:

 ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); engine.eval("var status=0; status++; println(status);"); //print 1 engine.eval("status++; println(status);"); //print 2 

If you use bindings, the variable defined in the script is the binding area, it will not pollute the area of โ€‹โ€‹the engines.

 ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); Bindings bindings=engine.createBindings(); //bindings.put("status",0); Bindings bindings2=engine.createBindings(); //bindings2.put("status",0); engine.eval("var status=0; status++; println(status);",bindings); //print 1 engine.eval("status++; println(status);",bindings2); // exception, status not defined 
+1
source

Source: https://habr.com/ru/post/1480029/


All Articles