65.9K
CodeProject is changing. Read more.
Home

Simple cross browser JavaScript get set

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Feb 7, 2012

CPOL
viewsIcon

19160

Simple cross browser JavaScript get set

I was doing research on JavaScript to see if there was finally a get set definition. And much to my surprise, there was:
function class(){
  var propertyName;

  this.__defineGetter__('propertyName', function(){
    return value;
  });

  this.__defineSetter__('propertyName', function(val){
    value = val;
  });
}
I was a little bothered by the formatting with both being functions instead of properties. But not that big of a deal. However, when I try it out and it doesn't work, I did some more research and discovered that it was only supported by FF and everything else was considered "legacy." The formatting of this new get-set definition gave me an idea though, based on some of my coding that uses assumed function arguments.
function class(){
  var propertyName;

  this.propertyName = function(val){

      if(typeof val != 'undefined'){
        propertyName = val;
      }
      else{
        return propertyName;
      }
  }
}
I have tested this in Chrome, Internet Explorer, Safari and Firefox. The way it works:
var class = new class();
class.propertyName('fooBar');

alert(class.propertyName());
When you call the function, it detects if an argument is passed. If it is, it sets the private variable and returns nothing; if it isn't, then it returns the current value of the private variable.