Click here to Skip to main content
Click here to Skip to main content

Tagged as

Simple cross browser JavaScript get set

, 14 Feb 2012
Rate this:
Please Sign up or sign in to vote.
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.

License

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

Share

About the Author

LordXandor

United States United States
No Biography provided

Comments and Discussions

 
Questionyou should use typeof PinmemberGottZ13-Feb-12 9:29 
AnswerRe: you should use typeof PinmemberLordXandor14-Feb-12 3:39 
GeneralRe: you should use typeof PinmemberVILIC VANE28-Jul-12 19:17 
GeneralRe: you should use typeof PinmemberLordXandor30-Jul-12 4:31 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140814.1 | Last Updated 14 Feb 2012
Article Copyright 2012 by LordXandor
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid