I have the following:
function Preferences() {
}
Preferences.players = {
'player1': new Player()
}
players is a static member variable of Preferences and I’m trying to make it an object containing an instance of a Player. However, it doesn’t appear to let me do this. It seems like it will allow me to define players if I make it a non-static member variable however. Like so:
function Preferences() {
var players = {
'player1' : new Player()
}
}
Is it possible to create a static member variable containing instances of an object in JS?
There are a couple of ways to do this. You can do it directly within the function:
Output:
Or as a prototype to a constructor function as Iggy Kay demonstrated.
Also, you can simulate static variables by using an anonymous function to create a closure:
Output:
Or the same as above, but with the module pattern:
Output: