If you are talking about variables, JavasScript has a 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 can be used.
You can call an anonymous function, but set the function context to your X object. Then this in 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) allows you to explicitly indicate that thisArg of a calling context. The first argument you pass will be how of a calling context. The first argument you pass will be how this` is defined in the context of the call.
Or just pass X as an argument.
var X = {}; (function(X){ XA = 5; XB = 8; XC = 7; })(X); for(a in X){ console.log(a+" is "+X[a]); }
Although itβs easiest to just refer to it (as I already noted in my answer above).
var X = {}; XA = 5; XB = 8; XC = 7; for(a in X){ console.log(a+" is "+X[a]); }
or use the module template:
global.myNamespace = (function(global,undefined) {
user113716
source share