简体   繁体   中英

Using the RhinoScriptEngine, how do I change what javascript keyword "this" refers to?

I am executing a third party javascript file in the RhinoScriptEngine. The file contains references to methods in "this". ie this.getField. The file is written with the expectation that "this" is some object other than the js Window object. So now when I run the script I'm getting this error:

Cannot find function getField in object [object Global]

Using the Java ScriptEngine (Rhino), how can I change the object "this" is referring to? Thanks!

Generally, I can call something like, scriptEngine.eval(script). This works great as long as there are no references to some global "this" object. I'd like to do something similar, but where I can define what "this" is.

I know this answer is over 3 years later, but if anyone finds their way to this page looking for a solution the following code worked for me:

ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript"); //Your Engine Name
engine.put("this", theObject);

Now referencing this will access the desired object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM