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 –

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.

No comments: