Multiple JavaScript Namespaces

I have a large js file that I want to split into several namespaces.

  • Is this a good / bad approach and supports everything in one namespace?

  • In NAMESPACE_FIRST, how can I call a map assembly?

    var NAMESPACE_FIRST = { init:function() { alert("onload functions"); }, this.map:function() { this.length = 0; }, this.map.prototype.build:function(){ return this.length; } }; var NAMESPACE_SECOND = { upload:function() { //do something }, delete:function() { //do something } }; $(function () { NAMESPACE_FIRST.init(); }); 
+4
source share
1 answer

Good question!

Firstly, your JavaScript is a little bit wrong. To achieve the effect that I think you need, your first namespace should look like this:

 var NAMESPACE_FIRST = { init: function() { alert("onload functions"); }, map: function() { this.length = 0; NAMESPACE_FIRST.map.prototype.build = function() { alert("1"); return this.length; } } } 

So, answering question 2, your onready will look something like this:

 $(function () { NAMESPACE_FIRST.init(); var obj = new NAMESPACE_FIRST.map(); obj.build(); } 

Regarding question 1, I have no real opinion anyway.

+1
source

All Articles