Van Coding Van Coding - 1 month ago 10
Javascript Question

Changing JavaScript's global object?

Is there a way to change the root object in JavaScript?

For example, in browsers, the root object is "window". So

X = 5;

is the same as:

window.X = 5;

What I want to do now, is changing this root object, so when I do the following:

X = 6;

Reason why I need this:

In Node.js applications, every part of the program can access the global object. That's a big problem because every script that is executed by a Node.js webserver can add new variables to it. They will be there until the webserver is restarted. I want to avoid this by changing the global object.


I've tested the following code and got a really interesting result.
What did you expect of the following code?

var X = {A:"a",B:"b"};

A = 5;
C = 7;
for(a in X){
console.log(a+" is "+X[a]);

Expected Console Output:
A is 5
B is b
C is 7

Real Console Output:
A is 5;
B is b;


Is there a way to get output as I expected it?


I've now tested the module system with the following code.

var t = require("./module.js");


A = 5;
exports.Test = function(){
console.log("hello world!");

The output was:

hello world!

This tells me, that the variable "A" defined in
was added to the global object of
. The module does not solve my problem, either.


There is the with statement, but it is not recommended and forbidden in strict mode.

It is better to refer to the variable holding the object explicitly.

In response to updated question:

with will search up the scope chain until it finds an object with a matching property or gets to window. It is no good for defining new properties on an object.

var X = { A: 5, B: 8, C: 7};
    console.log(A, B, C);