Skip to content Skip to sidebar Skip to footer

How Can I Add An Object Property To The Global Object In Rhino Javascript

I have some properties in an object that I would like to add to the global namespace. In javascript on the browser I could just add it to the window object like so: var myObject =

Solution 1:

I found a rather brilliant solution at NCZOnline:

functiongetGlobal(){
  return (function(){
    returnthis;
    }).call(null);
}

The key to this function is that the this object always points to the global object anytime you are using call() or apply() and pass in null as the first argument. Since a null scope is not valid, the interpreter inserts the global object. The function uses an inner function to assure that the scope is always correct.

Call using:

var glob = getGlobal();

glob will then return [object global] in Rhino.

Solution 2:

You could use this, which refers to the global object if the current function is not called as a method of an object.

Solution 3:

Here's how I've done it in the past:

// Rhino setupContextjsContext= Context.enter();
ScriptableglobalScope= jsContext.initStandardObjects();

// Define global variableObjectglobalVarValue="my value";
globalScope.put("globalVarName", globalScope, globalVarValue);

Solution 4:

You could just define your own window object as a top-level variable:

varwindow = {};

You can then assign values to it as you please. ("window" probably isn't the best variable name in this situation, though.)

See also: Can I create a 'window' object for javascript running in the Java6 Rhino Script Engine

Solution 5:

I've not used rhino but couldn't you just use var?

i.e.

var foo = myObject.foo;
foo();

Edit: Damn knew there'd be a catch! Miles' suggestion would be the go in that case.

Post a Comment for "How Can I Add An Object Property To The Global Object In Rhino Javascript"