Max
Max

Reputation: 4405

Javascript namespacing - is this particular method good practice?

I'm a javascript newbie, and I've come up with the following scheme for namespacing:

(function() {
    var ns = Company.namespace("Company.Site.Module");

    ns.MyClass = function() { .... };

    ns.MyClass.prototype.coolFunction = function() { ... };

})();

Company.namespace is a function registered by a script which simply creates the chain of objects up to Module.

Outside, in non-global scope:

var my = new Company.Site.Module.MyClass();

I'm particularly asking about the method by which I hide the variable ns from global scope - by a wrapping anonymous function executed immediately. I could just write Company.Site.Module everywhere, but it's not DRY and a little messy compared to storing the ns in a local variable.

What say you? What pitfalls are there with this approach? Is there some other method that is considered more standard?

Upvotes: 3

Views: 118

Answers (2)

Anders
Anders

Reputation: 17554

You dont need to scope classes like that, its only necessary if you have global variables outside of the class. I use this approach...

MyApp.MyClass = function() {
};

MyApp.MyClass.prototype = {
   foo: function() {
   }
};

Also note that I use a object literal for a cleaner prototype declaration

However if you need to scope global variables then you can do

(function() {
   var scopedGlobalVariable = "some value";

   MyApp.MyClass = function() {
   };
   MyApp.MyClass.prototype = function() {
       foo: function() {
       }
   };
})();

Upvotes: 1

Niko
Niko

Reputation: 26730

Your approach looks fine to me.

However, you can also do this slightly different, by returning the "class" from the self-executing function:

Company.Site.Module.MyClass = (function() {
    var MyClass = function() { ... };
    MyClass.prototype.foo = function() { ... };
    return MyClass;
})();

This strips at least all the ns. prefixes. The namespace function can still be utilized to create the objects, but outside of the self-executing function.

Upvotes: 1

Related Questions