Get and Set operators in Javascript

I am C# developer, hence I use C# properties a lot. However I just recently discovered that Javascript has properties as well. Get and Set operators supported by Firefox 2.0+, Safari 3.0+, Chrome, Opera 9.5+. However IE still doesn't support properties. May be Microsoft would introduce support in IE10, but so far no luck. Here is a little example of Get and Set declaration:

var obj = {
 
   get CustomProperty() {
     return 0;
   },
 
   set CustomProperty(s) {
     alert ("It is readonly.");
   }
};

 

Properties can be useful and scary at the same time. A simple variable assignment is not predictable anymore. For example with a little bit of work you can convert your AJAX calls to something like this:

ajax.url = "script.php";
 
alert(ajax.result);

 


Posted on Saturday, February 4, 2012 by | Add Comment

New Comment

Your Name:
Email (for internal use only):
Comment:
 
Code above:

Categories

Recent Tweets

  • Simon Ince's Blog: Hierarchies with HierarchyID in SQL 2008 http://t.co/xSDwiF6rRS.
  • Visual Studio 2010 WAS painfully slow - CodeProject http://t.co/Usba1x6CZy

Valid HTML5