开发者

Static member variable containing object instances

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 v开发者_开发问答ariable 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:

var foo = function() {
    if ( typeof foo.static == "undefined" ) {
        foo.static = Math.random();
    }
};

console.log(foo.static);
foo();
console.log(foo.static);
foo();
console.log(foo.static);

Output:

undefined
0.33120023757048356
0.33120023757048356

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:

var Foo = (function() {
    var static = {x: Math.random(), etc:3};

    // Instantiable object
    return function() {
        this.a = Math.random();

        this.bar = function() {
            console.log(this.a, static);
        };
    };
})();

var f1 = new Foo(), f2 = new Foo(), f3 = new Foo();
f1.bar();
f2.bar();
f3.bar();

Output:

0.318481237168568   Object { x=0.35319106907436637, more...}
0.5422140103705965  Object { x=0.35319106907436637, more...}
0.30933348253602777 Object { x=0.35319106907436637, more...}

Or the same as above, but with the module pattern:

var Foo = (function() {
    var static = {x: Math.random(), etc:3};

    // Module pattern
    return function() {
        return {
            a: Math.random(),
            bar: function() {
                console.log(this.a, static);
            }
        };
    };
})();

var f1 = new Foo(), f2 = new Foo(), f3 = new Foo();
f1.bar();
f2.bar();
f3.bar();

Output:

0.2368968219817239 Object {  x=0.17619776914569862,  more...}
0.5411810225426568 Object { x=0.17619776914569862, more...}
0.3319039598508573 Object { x=0.17619776914569862, more...}


If you intend to have multiple instances of Preferences sharing the static list of players, you can put them in the prototype:

function Preferences(){}
Preferences.prototype.Players = {'player1': new Player() }; 

var pref1 = new Preferences();
alert(pref1.Players.player1); 

var pref2 = new Preferences();
alert(pref2.Players.player1); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜