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...}