Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 659
Max Avatar asked Aug 29 '26 04:08

Max


1 Answers

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() {
       }
   };
})();
like image 179
Anders Avatar answered Aug 31 '26 16:08

Anders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!