简体   繁体   English

使用 RhinoScriptEngine,如何更改 javascript 关键字“this”所指的内容?

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

I am executing a third party javascript file in the RhinoScriptEngine.我正在 RhinoScriptEngine 中执行第三方 javascript 文件。 The file contains references to methods in "this".该文件包含对“this”中方法的引用。 ie this.getField.即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:编写文件时期望“this”是 object 而不是 js Window object。所以现在当我运行脚本时出现此错误:

Cannot find function getField in object [object Global]在 object [object Global] 中找不到 function getField

Using the Java ScriptEngine (Rhino), how can I change the object "this" is referring to?使用 Java ScriptEngine (Rhino),如何更改“this”所指的 object? Thanks!谢谢!

Generally, I can call something like, scriptEngine.eval(script).通常,我可以调用类似 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.只要没有对某些全局“this”object 的引用,这就很好用。我想做类似的事情,但我可以定义“this”是什么。

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:我知道这个答案已经过了 3 年多了,但是如果有人找到了这个页面来寻找解决方案,那么以下代码对我有用:

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

Now referencing this will access the desired object.现在引用this将访问所需的 object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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