Subj : Re: How to use Rhino scopes in a multithreaded environment To : netscape.public.mozilla.jseng From : Attila Szegedi Date : Thu Mar 10 2005 07:06 pm That's because regardless of you passing "scope" to foo as its scope, it will still execute with sharedScope as its scope (and hence won't see "out") - this is how static scoping works. If you invoke cx.compileString() from a Context that returns true for hasFeature(FEATURE_DYNAMIC_SCOPE), then the generated Function objects will not ignore the passed scope object - that's how dynamic scoping works and that's what you want. The only way I know of to turn on dynamic scoping is to create a subclass of ContextFactory, override its hasFeature() method, and then use ContextFactory.initGlobal() to install that custom context factory as *the* context factory used by Context.enter() to create contexts. Attila. -- home: http://www.szegedi.org weblog: http://www.jroller.com/page/aszegedi Visit Szegedi Butterfly fractals at: http://www.szegedi.org/fractals/butterfly/index.html On 6 Mar 2005 02:37:35 -0800, ant wrote: > I'm embedding Rhino in a multithreaded environment and I'm trying to > understand how scopes work based on the info at > http://www.mozilla.org/rhino/scopes.html > > I'd like to use a scope shared across threads which contains compiled > function definitions, and for each thread to have its own scope for > running calls to those functions. I'd also like to be able to add some > custom objects to the thread specific scope for use by the function > calls. > > The problem is the functions don't seem to find the objects I add to > the thread specific scope. The following code demonstrates the > problem: > > public class Test { > > public static void main(String[] args) { > Context cx = Context.enter(); > try { > > Scriptable sharedScope = cx.initStandardObjects(null, true); > > String script = "function foo() {out.println(\"in foo\");}"; > Script compiledScript = cx.compileString(script,"bla",1,null); > compiledScript.exec(cx, sharedScope); > Function foo = (Function) sharedScope.get("foo", sharedScope); > > Scriptable scope = cx.newObject(sharedScope); > scope.setPrototype(sharedScope); > scope.setParentScope(null); > > Object wrappedOut = Context.javaToJS(System.out, scope); > ScriptableObject.putProperty(scope, "out", wrappedOut); > > foo.call(cx, scope, scope, new Object[] {}); > > } finally { > Context.exit(); > } > } > } > > Running this fails with: Exception in thread "main" > org.mozilla.javascript.EcmaError: ReferenceError: "out" is not > defined. (bla#1) > > What am I doing wrong? > .