Using namespaces (modules) in Javascript

Recently I’ve been developing my own GUI engine in Javascript.

Nothing fancy, however it is quite big so I’ve decided to use namespaces (modules).

After reading some tutorials I’ve found Gravatar comment here.

I’ve really liked his method so I’ve decided to use it in my own projects. If you want to use namespaces, place this piece of code before any other JS stuff:

String.prototype.namespace = function(source) {
    Object.extend(this.split('.').inject(window, function(parent, child) {
        return (parent[child] = parent[child] || { });
    }), source || { });
}

Now You can use namespaces like this:

'Space.Subspace.Methods'.namespace({
    method: function(){
        alert('h hello world!');
    },
    method2: function(){
        alert('bye bye worlds!')
    }
});

After defining module, using its method is quite easy:

    Space.Subspace.Methods.method();
    Space.Subspace.Methods.method2();

There’s more! Creating classes inside modules. First our base class (Class.create is a part of Prototype library):

var Parent = Class.create({
    class_method: function(){
        alert('im here!')
    }
});

Inheritance and namespace:

'Space.Subspace.Klasses'.namespace({
    SuperClass: Class.create(Parent, {})
});

I nie pozostaje nam nic innego jak utworzyć instancję klasy i sprawdzić czy działa:

    a = new Space.Subspace.Klasses.SuperClass();
    a.class_method();
02
May 2010
POSTED BY
POSTED IN Javascript
DISCUSSION 0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *


*

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