Click here to Skip to main content
15,510,771 members
Articles / Programming Languages / Javascript
Tip/Trick
Posted 7 Feb 2012

Tagged as

Stats

18K views
3 bookmarked

Simple cross browser JavaScript get set

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
14 Feb 2012CPOL
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:

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

JavaScript
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:

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionyou should use typeof Pin
GottZ13-Feb-12 10:29
GottZ13-Feb-12 10:29 
AnswerRe: you should use typeof Pin
LordXandor14-Feb-12 4:39
LordXandor14-Feb-12 4:39 
You are absolutely right. When I made this, the coding that I took if(val){}else{} from that would cause undesired effects. But I did not think about it when making the get set.

Thank you very much, I have made the edit above. Except that I used != instead simply for the personal preference of putting the return in the else statement. But it could be flipped around to work either way.
GeneralRe: you should use typeof Pin
VILIC VANE28-Jul-12 20:17
VILIC VANE28-Jul-12 20:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.