I’m just trying to understand Javascript a little deeper.
I created a ‘class’ gameData that I only want ONE of, doesn’t need a constructor, or instantiated.
So I created it like so…
var gameData = new function () {
//May need this later
this.init = function () {
};
this.storageAvailable = function () {
if (typeof (Storage) !== "undefined") {
return true;
}
else {
return false;
}
};
}
Realizing that the ‘new’ keyword doesn’t allow it to be instantiated and makes it available LIKE a static class would be in C#.
Am I thinking of this correctly? As static?
No, it is not static because it still has a
constructorproperty pointing to your “anonymous” function. In your example, you could useto reinstantiate a second object, so the “class” (instance actually) is not really “static”. You are basically leaking the constructor, and possibly the data that is bound to it. Also, a useless prototype object (
gameData.constructor.prototype) does get created and is inserted in the prototype chain ofgameData, which is not what you want.Instead, you might use
This is what the singleton pattern would look like:
Yet, the prototype is quite useless because you have only one instance of
GameData. It would only get interesting with inheritance.