If you want a constructor, why not use a constructor?
var MyGlobalVar = new function() {
// run whatever code you want in here
// The new object being constructed is referenced via "this"
this.Property1 = 1;
this.Property2 = "Two";
};
This code uses an anonymous function as the constructor. You can run whatever code you want inside. The new object is referenced by this, and it is returned automatically, so MyGlobalVar will look like:
{
Property1: 1,
Property2: "Two"
}
Another approach, and one that is perhaps more common than using an anonymous constructor, is to use a module pattern. It is very similar, but it doesn't use the function as a constructor by calling it with new, and it just returns an object literal.
The above code would be rewritten like this:
var MyGlobalVar = (function() {
// run whatever code you want in here
// The new object is an object literal that we create and return
var _new_obj = {
Property1: 1,
Property2: "Two"
};
return _new_obj;
})();
Just like the first example, it gives you an enclosed environment where you can run whatever code you need in creating the values to be referenced by your object.
The end result is practically identical. The only real difference is that the prototype chain of the object in the first example looks like:
_new_obj ---> {} ---> Object.prototype ---> null
whereas the prototype chain in the new version looks like:
_new_obj ---> Object.prototype ---> null
So there's a slightly shorter chain. It won't make such a difference that you should base any decision on it.