Van Coding Van Coding - 11 days ago 6
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;
console.log(Y);


is the same as:

window.X = 5;
console.log(window.Y);


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.

Update

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"};

with(X){
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?

Update

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

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

console.log(A);

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


The output was:

hello world!
5


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

Answer

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};
with(X){
    console.log(A, B, C);
}