Thursday 22 July 2010

Rhino - Part2 - Scope Sharing/Parent Scope

As specified in this post, you don't need to create a scope from scratch.
A scope object can be created using already existing scope where already existing scope behaves like a parent scope.

E.g. localScope object can be created using globalScope, so that local scope can inherit global scope.
This can be done as follows –
Scope localScope = context.newObject(globalscope, );
where constructor_name = name of the constructor which will be used in order to create the scope. This constructor definition is present in globalscope.

If global scope has been shared among different local scope objects, then if global scope changes due to execution of any script using any of the local scopes, then this change is reflected in all the local scopes.
e.g. suppose, G = global scope, L1, L2 = local scopes derived from G.
S1 and S2 are the script objects.
Say, “a” is a global variables value of which is 5.
If on S1.execute(cx,L1), a becomes 10, then this change gets reflected in both L1 and L2.

If we don’t need this change to be reflected in all the other local scopes, then we can do following –
L1.setPrototype(G);
L1.setParentScope(null)

This creates a clone of G for L. And setting parent scope to null removes the parent scope. (This whole shifts the role of global scope from parent scope to prototype). This is called prototype-based inheritance. Check Proototype based programming.

Rhino API - Introduction

Use: To execute Javascript from java classes.

How Rhino achieves it -
To execute any code what all needed is the context i.e. call stack, local registers etc and the scope which contains all lookup variables and functions. Source gets compiled to produce object files. And object files are used for execution. Rhino uses the same concept for Javascript execution.

Steps:
1) Create Context (Context cx = Context.enter())
2) Initialize scope (Scriptable scope = cx.initializeStandardObjects())
3) Populate scope(scope.put(name,value))
4) Compile the script (Script script = cx.compileScript(String scriptSource)
5) Execute the script (script.execute(cx,scope))

Context = It represents runtime context which contains all the information for execution of javascript.
Scope = it contains standard variables, functions, their definitions which are looked up while execution of javascript.
Script = It is an output of compilation of javascript. (Like a .class file for java class)

Check this.