Better JavaScript Object Creation

by rsutton 30. December 2009 06:36

So I’ve decided that I don’t like the two general ways of creating objects in JavaScript so I’ve decided to create my own.  This one is partially inspired by ruby :)

    1 

    2 Hello = function() {

    3     return {

    4         new: function(a,b) {

    5             return {

    6                 one: a,

    7                 two: b,

    8                 talk: function() {

    9                     alert('hello: ' + a + ' ' + b);

   10                 }

   11             };

   12         }

   13     }

   14 }();

   15 

I am using the object literal notation to create the object.  Generally this notation works well until you want multiple instances of the object you are creating.  This is why I have added the new method.  This new method acts as a constructor and will return a function.  This function creates a closure and so all the properties (one,two) and methods (talk) will be unqiue to each “instance”.

So usage would be like this:

world = Hello.new(‘my’,’world’);
universe = Hello.new(‘my’,’universe’);

alert(world.b); // “world”
alert(world.talk()); // “hello: my world”
alert(universe.b); // “universe”
alert(universe.talk()); // “hello: my universe”

As you can see each “instance” is unique.  What makes this instance unique is that you are actually not dealing with the Hello object directly, but with the new function on the hello object.  It is important to place everything inside the new function so that all the variables and functions will be unqiue to each instance.

Good luck!

Tags:

Development

Comments

Comments are closed

Powered by BlogEngine.NET 1.4.5.0
Theme by Extensive SEO

Profile

Member of the Church of Jesus Christ of Latter-Day Saints, Developer and IT Professional