How are Rhino native functions created?

I looked at the Rhino documentation and source code to determine how to implement my own global function. However, this task is more difficult than I expected.

After reading the implementation code for the require function in RingoJS, I believe that I need to do something in the following lines:

 import org.mozilla.javascript.BaseFunction; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.Context; public class MyGlobalNativeFunction extends BaseFunction { public MyGlobalNativeFunction() {} public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { // implementation of my function } public int getArity() { return 1; } } 

Am I on the right track? A step-by-step walkthrough on how to achieve this would be great.

It would also be great if I could use the Rhino defineClass function to create my global inline function. I'm not too keen on developing my own modified version of Rhino just because I want to implement one of my own functions.

+4
source share
2 answers

I think this should work, and if you want to implement only one global function, this is a good approach. If you want to implement several functions or a host object, there are other approaches.

Then you would use something like this to instantiate your function:

 scope.defineProperty("myNativeFunction", new MyGlobalNativeFunction(), ScriptableObject.DONTENUM); 

Give up on RingoGlobal for how this is done (it also shows how to define several functions in one scan without having to create a class for each). The Rhino sample directory contains some examples of how to create the right host objects with Rhino.

+4
source

First of all, you need to start your global scope (initialize the entire standard javascript object, functions, etc.), and then add your function to this area, as Hannes Wannofer wrote.

 Context cx = Context.enter(); //enter rhino context - bind context with current thread Scriptable globalScope= cx.initStandardObjects(); //init js standard object in global scope globalScope.defineProperty("myNativeFunction", new MyGlobalNativeFunction(), ScriptableObject.DONTENUM); 

and what is he.

Now to call this function, call:

 Object result = cx.evaluateString(globalScope, "myNativeFunction()", "<cmd>", 1, null); 

See the rhino introduction tutorial for more information.

+4
source

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


All Articles