How can I add an object property to the global object in rhino javascript

后端 未结 5 1900
迷失自我
迷失自我 2021-02-15 18:48

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:

5条回答
  •  無奈伤痛
    2021-02-15 18:57

    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.

提交回复
热议问题