Changing JavaScript's global object?

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

If you're talking about variables, JavasScript has function scope.

X = 5;  // global variable

console.log( window.X );  // 5

(function() {
   var X = 6;  // declare a local variable by using the "var" keyword

   console.log( X );  // 6
})();

console.log( window.X );  // 5

Otherwise, you can create an Object, and add properties to it.

X = 5; 

console.log( window.X );  // 5

var obj = {};

obj.X = 6;

console.log( obj.X ); // 6

console.log( window.X );  // 5

EDIT: Adding another possible solution that could be used.

You could invoke an anonymous function, but set the context of the function to your X object. Then this in the function will refer to X.

var X = {};
(function(){
    this.A = 5;
    this.B = 8;
    this.C = 7;
}).call(X);
for(a in X){
    console.log(a+" is "+X[a]);
}

The .call() method (as well as the .apply() method) allow you to explicitly set the thisArgof a calling context. The first argument you pass will be howthis` is defined in the context of the invocation.

Or just pass X in as an argument.

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

Though the simplest is to simply reference it (as I noted in my answer above).

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

or use a module pattern:

   /****** I'm guessing at the use of "global" here ********/
global.myNamespace = (function(global,undefined) {

    // define the object to be returned
    var X = {};

    //  define private local variables
    var a_local = 'some value';
    var another_local = 'some other value';

    // define private functions
    function myFunc() {
        // do something with local variables
    }

    // give the return object public members
    X.someProperty = 'some value';
    X.anotherProperty = 'another value';
    X.publicFunc = function() {
        //do something with the local variables
        //    or public properties
    };
    X.anotherFunc = function() {
        //do something with the local variables
        //    or public properties
    };
    // return the object
    return X;

})(global);

console.log(myNamespace);

Tags:

Javascript