How can I add an object property to the global obj

2019-04-07 02:01发布

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?

5条回答
淡お忘
2楼-- · 2019-04-07 02:03

I found a rather brilliant solution at NCZOnline:

function getGlobal(){
  return (function(){
    return this;
    }).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.

查看更多
Summer. ? 凉城
3楼-- · 2019-04-07 02:08

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);
查看更多
唯我独甜
4楼-- · 2019-04-07 02:09

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: Can I create a 'window' object for javascript running in the Java6 Rhino Script Engine

查看更多
倾城 Initia
5楼-- · 2019-04-07 02:11

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.

查看更多
Fickle 薄情
6楼-- · 2019-04-07 02:18

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

查看更多
登录 后发表回答