KARPACH

WEB DEVELOPER BLOG

Get and Set operators in Javascript

I am a 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. Maybe Microsoft would introduce support in IE10, but so far no luck. Here is a little example of a 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 February 4, 2012 by