I just learned this way of initializing a variable in javascript:
var MyGlobalVar = {
Property1 : 1,
Property2 : "Two"
}
Which is pretty neat because is a lot like a static object. But is there any way I can run initialization code inside it, kinda like a static constructor would do?
How about using eval, such as Property1 : eval("[code to run here...]");?
I just don’t want to put any initialization or part of my object’s definition outside the object itself (outside the brackets).
Edit: My initialization code would actually return a filled up array, so Property2 would be this array. But I don’t want to recreate this array every time is needed.
If you want a constructor, why not use a constructor?
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, soMyGlobalVarwill look like: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:
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
prototypechain of the object in the first example looks like:whereas the prototype chain in the new version looks like:
So there’s a slightly shorter chain. It won’t make such a difference that you should base any decision on it.