views:

435

answers:

5

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 = {
  foo : function() {
    alert("hi");
  }
  // and many more properties
};

for (property in myObject) {
  window[property] = myObject[property];
}

// now I can just call foo()
foo();

But since rhino doesn't have the global window object I can't do that. Is there an equivalent object or some other way to accomplish this?

A: 
rezzif
Hah! Too simple for me :) Thanks!
timdisney
Ah, wait...here's my real problem. I want to do this programmaticaly. I don't actually know the names of the object properties before hand.
timdisney
+3  A: 

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

Miles
var window = this; at the very beginning of the script helped me out. See the env.js script by John Resig http://ejohn.org/blog/bringing-the-browser-to-the-server/
GrGr
A: 

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

var window = {};

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

See also: http://stackoverflow.com/questions/964392/can-i-create-a-window-object-for-javascript-running-in-the-java6-rhino-script-e

harto
+1  A: 

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

// Rhino setup
Context jsContext = Context.enter();
Scriptable globalScope = jsContext.initStandardObjects();

// Define global variable
Object globalVarValue = "my value";
globalScope.put("globalVarName", globalScope, globalVarValue);
edsoverflow
+1  A: 

I found this rather brilliant solution at NCZOnline He proposes a function that return the global object no matter what context

function getGlobal(){
  return (function(){
    return this;
    }).call(null);
}

then you can call

var glob = getGlobal();

glob will then return [object global] in Rhino.

pnewhook
Brilliant! Remember that this will not work in ES5 strict mode, so your script may fail once Rhino [introduces ES5-conformance](https://bugzilla.mozilla.org/show_bug.cgi?id=517860).
Pumbaa80