Simulating Static behaviour for Object Properties in JavaScript

01 / Feb / 2013 by Shreyance Jain 0 comments

We were facing problem at time of creating Static properties in any Object in JavaScript as there is not any direct method to create static properties. For example if we want to create a static property in an array object and we want it to be same for every other object without storing the property in objects by which object’s size will not increased and actual static property is stored in another place which is accessed by every object. In the process we created following method to get Static like behavior¬† in JavaScript.


(function () {
   var statics = {};
   Array.prototype.static = function (name, value) {
     if (!Boolean(value)) {
       return statics[name];
     }
     else {
       statics[name] = val;
     }
   }
 })(); //this method will create a static method in Array's prototype by calling which any object can get and set the value of static element.

 [].static("first","hello");
 [].static("out","this is static");
 var array = [10,20,30]
 console.log(array.static("first")); // prints "hello"
 console.log(array.static("out")); // prints "this is static"

Shreyance Jain
shreyance@intelligrape.com

Tag -

FOUND THIS USEFUL? SHARE IT

Leave a comment -