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

初次使用NodeJS构建RESTful服务

最近要给项目组用NodeJS写一个简单的RESTful. 在网上简单查了些资料。首先需要在服务器上安装NodeJS以及npm(NodeJS包管理工具). 这里不在重复安装的过程.

安装好这些, 然后需要安装webservice, mysql等模块.

npm install webservice mysql

安装完成之后. 创建一个目录demo, 并且创建一个server.js以及demo.js

Read more »