Hello,

I found myself quite surprised after a lengthy debugging session. It seems I
don't have a good understanding of contexts and scopes. Perhaps someone can
enlighten me. Here's a heavily trimmed down sample of how I use Rhino:

String javaScript ...
String functionName = "myFunction";
Context context = ContextFactory.getGlobal().enterContext();
// try/catch omitted for brevity
executionCount++;
if (executionCount == 1) {
... set up context
}
// Initialize the standard objects (Object, Function, etc.)
// This must be done before scripts can be executed.
Scriptable scope = context.initStandardObjects(this); // "this" is just a
class of mine that runs JavaScript
// Run the script
context.evaluateString(this, javaScript, "<" + scriptedEntityId + ">", 1,
null); // maybe the problem is "this" here?
Object fObj = scope.get(functionName, scope);
if (fObj instanceof Function) {
Function function = (Function) fObj;
result = function.call(context, scope, scope, functionArgs);
}

Each time I run JavaScript I am "compiling" it from text. Sometimes the
JavaScript being run calls Java which in turn runs more JavaScript. I have a
case where I first run JavaScript that defines a function "myFunction()" and
I call that function as above. Then, in the same thread/context I run
another block JavaScript that does NOT define "myFunction()" but I call it
just as above, trying to get a function named "myFunction()". Much to my
surprise, this second running finds the "myFunction()" definition from the
first running. It was my understanding prior that the things I define,
properties or functions get defined in the scope, not the context. Can
someone tell me what's going on and how I can rearrange my code so the
attempt to call myFunction when it's not in the javaScript, nothing happens?

The code above is from a class like so:

public class JavaScriptEvaluator extends ScriptableObject {

Perhaps the error is in this line:
context.evaluateString(this, javaScript, "<" + scriptedEntityId + ">", 1,
null); // maybe the problem is "this" here?

I wrote this code ages ago and can't remember why I used "this" for the
"scope" argument (or why this class is Scriptable). Should I have used
"scope"? I always use the same JavaScriptEvaluator instance for the entire
thread, so I guess that could mean I'm using the same scope for the whole
thread which is not my intention. It all seems pretty obvious now, but I'm
not really sure what to do, so thoughts appreciated.

Thanks.


-- 
Daryl Stultz
_____________________________________
6 Degrees Software and Consulting, Inc.
http://www.6degrees.com
http://www.opentempo.com
mailto:[email protected]
_______________________________________________
dev-tech-js-engine-rhino mailing list
[email protected]
https://lists.mozilla.org/listinfo/dev-tech-js-engine-rhino

Reply via email to