Call a function when a property gets set on an object

Viewed 9583

I don't really know how to explain this but I'll show you code and tell you what I'd like to achieve.

Let's say I make a quick object:

var test = {};

And then I set a property to it: (I insist on the syntax, it mustn't use any function as the setter)

test.hello = 'world';

Pretty simple, eh? Now I'd like to add a function to that object that would get called everytime a new property gets set. Like this:

var test = { 
                newPropertyHasBeenSet: function(name){ 
                    console.log(name + 'has been set.'); 
                } 
            };

test.hello = 'world';

// Now newPropertyHasBeenSet gets called with 'hello' as an argument.
// hello has been set.

I don't know if it's possible, but that would be quite amazing. Anyone has an idea of how to achieve so?

EDIT: I'd like also to be able to do the same for property get (so test.hello would call get('hello') for example).

EDIT2: This is for server-side javascript using node.js.

Thanks a lot and have a nice day!

5 Answers
Related