有几个方法可以做到这一点。您可以直接在函数中做到这一点:
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...}
第一个应该工作。你看到什么问题? – 2010-05-30 04:49:19
习惯上接受你的问题的答案,以便其他用户知道你已经获得了你需要的信息。 – 2010-06-04 03:45:48