Custom Search

In this blog you'll find some technological updates and comments to events in the software engineering world.

Wednesday, 7 October 2009

Creating simple objects in javascript

If you want a simple way to create objects in javascript, without having to use the prototype. Here you go:

As javascript is a very cool language a function can actualy return other functions. These functions will have access to the "parent"'s inner variables, but won't have access to the other returned functions.

So you can create an object in javascript like:


function myObject(var_a, another_var)
var x = var_a;
var y = another_var;

return {
getString: function(){
return x+" "+y;
},
add: function(){
return x*1+y*1; //multiplying by 1 forces a cast to int
}
}
}


With this you created an object called myObject, which is nothing more than a function, that returns functions.

The returned functions have access to x and y but can't access var_a and another_var.

You can call this object like:

var bla = myObject(3,2);
alert(bla.add());
which gives you an alert popup saying "5"

Or just

alert(myObject().getString());
which gives you an alert saying "1 2"

Hope this can help someone :)