Static variables in javascript

Sometimes we want to do stuff in javascript that simply cannot be done. But, that doesn't stop us from cheating our way through. Below a simple hack to get static variables in javascript that you can access from outside and within the object.

myDemoObject = function(name) { this.demoname = name };
myDemoObject.options= new Array("country", "world","universe");
myDemoObject.prototype.options = myDemoObject.options;
myDemoObject.prototype.makeruler = function() {
   return this.demoname + " is the ruler of " + 
         this.options[ Math.floor( 
                         Math.random()*this.options.length 
                      ) ] ;
}

mark = new myDemoObject("Mark Twain");
console.log(mark.makeruler());
console.log("But I wonder if he's the ruler of the " 
             + myDemoObject.options[ Math.floor( 
                Math.random()*myDemoObject.options.length 
             ) ] );

We managed to make the "static" object that holds reference to a single object(just like the static variables) everywhere.

myDemoObject.options= new Array("country", "world","universe");
myDemoObject.prototype.options = myDemoObject.options;

The thing to keep in mind though is that this is not a true static object!

if you change this.options with something else entirely like:

this.options = somethingnew;

myDemoObject.options does not change to somethignnew. The same goes viceversa.

But if you do this.options.push("multiverse"); myDemoObject.options will change to hold the new array item.

This is because myDemoObject.options and this.options hold the reference to the same exact object.So basically if you wish to alter something on the "static" variable make sure you make a change in the object instead of altering the reference to the object.

So in conclusion, you can have a somewhat static object in your Objects, as long as you keep from the temptation to override them to a whole new variable.

When Object.observe really comes through you can work your way around this last flaw by having auto updaters of the object, but until then you have to mind it yourself.

Comments