[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/

Leave a Comment

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: