我有以下几点:
function Preferences() {
}
Preferences.players = {
'player1': new Player()
}
players是Preferences的静态成员变量,我正在尝试使其成为包含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...}
关于javascript - 包含对象实例的静态成员变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2937570/