Defining Getters and Setters in NodeJS

Recently I discovered something interesting while messing around with NodeJS… you can define getters and setters using the ECMAScript5 syntax. For a useless example I could do something like this:

This is kind of boring though because it’s just a more complicated way of doing

however you can notice in the first example you can add any kind of custom behavior to the getter and setter and access it via person.age. Where this does become useful however is if you want to create a read only property, which you can do by just defining the getter alone:

This will print the initial age as expected, however the last line where the attempt is made to set the property will throw the exception “TypeError: Cannot set property age of #<a Person> which has only a getter.”

A small discovery, yet very useful. ;)

You can leave a response, or trackback from your own site.

Facebook comments:

One Response to “Defining Getters and Setters in NodeJS”

  1. Luke Smith says:

    Another syntax supported by ES5 and NodeJS is

    var obj = {
    _foo: "unset",

    get foo() {
    return this._foo;
    },

    set foo(val) {
    this._foo = "Value of foo is now " + val;
    }
    };

    sys.puts(obj.val); // "unset"
    o.foo = "a new value";
    sys.puts(obj.val); // "Value of foo is now a new value"

Leave a Reply

Subscribe to RSS Feed Follow me on Twitter!