Category Archives: NodeJS

[RT] 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:

var sys = require('sys')

function Person(age){
this.__defineGetter__('age', function(){
return age
})

this.__defineSetter__('age', function(arg){
age = arg
})
}

var dude = new Person(18)

sys.puts(dude.age)
dude.age = 32

sys.puts(dude.age)

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

function Person(age){
this.age = age
}

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:

var sys = require('sys')

function Person(age){
this.__defineGetter__('age', function(){
return age
})
}

var dude = new Person(18)

sys.puts(dude.age)
dude.age = 32

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 # which has only a getter.”

A small discovery, yet very useful.

This origin post url: http://blog.james-carr.org/2010/07/19/defining-getters-and-setters-in-nodejs/