含静态成员变量的对象实例
问题描述:
我有以下几点:含静态成员变量的对象实例
function Preferences() {
}
Preferences.players = {
'player1': new Player()
}
球员是首选的静态成员变量,我想使它包含播放器的一个实例的对象。但是,它似乎没有让我这样做。看起来像将允许我定义球员,如果我把它作为一个非静态成员变量但是。像这样:
function Preferences() {
var players = {
'player1' : new Player()
}
}
是否有可能在JS中创建一个包含对象实例的静态成员变量?
答
有几个方法可以做到这一点。您可以直接在函数中做到这一点:
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);
输出:
undefined
0.33120023757048356
0.33120023757048356
或者为原型,以展示一个构造函数为Iggy Kay。
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();
输出:
0.318481237168568 Object { x=0.35319106907436637, more...}
0.5422140103705965 Object { x=0.35319106907436637, more...}
0.30933348253602777 Object { x=0.35319106907436637, more...}
还是和上面一样,但与模块模式:
另外,还可以通过使用匿名函数创建一个关闭模拟静态变量
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();
输出:
0.2368968219817239 Object { x=0.17619776914569862, more...}
0.5411810225426568 Object { x=0.17619776914569862, more...}
0.3319039598508573 Object { x=0.17619776914569862, more...}
答
如果您打算有偏好分享玩家的静态列表的多个实例,你可以把他们的原型:
function Preferences(){}
Preferences.prototype.Players = {'player1': new Player() };
var pref1 = new Preferences();
alert(pref1.Players.player1);
var pref2 = new Preferences();
alert(pref2.Players.player1);
第一个应该工作。你看到什么问题? – 2010-05-30 04:49:19
习惯上接受你的问题的答案,以便其他用户知道你已经获得了你需要的信息。 – 2010-06-04 03:45:48