If you want to achieve this, there are a few different methods you can use. One approach is to directly implement it 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);
Result:
undefined
0.33120023757048356
0.33120023757048356
Alternatively, you can utilize a prototype in a constructor function as shown by Iggy Kay.
Another way is to simulate static variables 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();
Result:
0.318481237168568 Object { x=0.35319106907436637, more...}
0.5422140103705965 Object { x=0.35319106907436637, more...}
0.30933348253602777 Object { x=0.35319106907436637, more...}
Or you can follow the same concept 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();
Result:
0.2368968219817239 Object { x=0.17619776914569862, more...}
0.5411810225426568 Object { x=0.17619776914569862, more...}
0.3319039598508573 Object { x=0.17619776914569862, more...}