Using ECMAScript 5 Getters and Setters With NodeJS

By Kip Lawrence, published 2010-09-24

Did you know you could use ECMAScript 5 features in NodeJS? You can! Try this getter and setter example:

var obj = (function() {
  var a;
  return { 
    get a() { 
      return a;
    },

    set a(v) {
      a = 'prepender: ' + v;
    }
  }; 
})();
obj.a = "Hi";
console.log(obj.a);

Running the code gives you the following: [text light="true"] $ node test1.js prepender: Hi [/text] In the obj function you can not access the a variable directly. Instead you have to access it through the getter and setter. You could use code like this to validate your data before you set a, etc... How cool it this!

About the Author

Name:
Kip Lawrence
Location:
Lindon, UT
Github:
mightykip
Twitter:
mightykip

Kip Lawrence is a software developer who lives in Lindon, Utah. Computers started as a hobby for him and later turned in to a career. His first programming language was Basic on a Commodore 64. Since those early days he has dabbled in assembly, Pascal, C, C++, Python, Java, Objective-C, Perl and JavaScript. He currently works as a Senior Software Engineer at Domo Technologies, Inc.

About UtahJS.com

UtahJS is the website for the Utah JavaScript Users Group that meets to discuss and enjoy JavaScript!

JavaScript in the browser, on the server or just about anywhere else.

We love JavaScript but quite often talk about other topics such as CSS, HTML, cross browser coding, the internet… pretty much, anything that we find interesting.

Everyone is welcome. Please join us!