JavaScript namespace declaration

I created a javascript class as follows:

var MyClass = (function() { function myprivate(param) { console.log(param); } return { MyPublic : function(param) { myprivate(param); } }; })(); MyClass.MyPublic("hello"); 

The code above works, but my question is how I want to introduce a namespace in this class.

Basically, I want to be able to call the class as follows:

 Namespace.MyClass.MyPublic("Hello World"); 

If I add Namespace.MyClass, it will throw a syntax error. I tried to add "window.Namespace = {}" and it does not work either.

Thank..:)

+28
javascript
Mar 24 '10 at 0:15
source share
8 answers

I usually recommend doing this (assuming Namespace not defined elsewhere):

 var Namespace = {}; Namespace.MyClass = (function () { // ... }()); 

A more flexible but more complex approach:

 var Namespace = (function (Namespace) { Namespace.MyClass = function() { var privateMember = "private"; function myPrivateMethod(param) { alert(param || privateMember); }; MyClass.MyPublicMember = "public"; MyClass.MyPublicMethod = function (param) { myPrivateMethod(param); }; } return Namespace }(Namespace || {})); 

This will build Namespace.MyClass as described above, but does not rely on an existing Namespace . He will declare and create it, if he does not already exist. It also allows you to load multiple Namespace elements in parallel in different files, the order of loading does not matter.

More details: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

+43
Mar 24 '10 at 1:17
source share

YUI has a nice method for declaring namespaces

 if (!YAHOO) { var YAHOO = {}; } YAHOO.namespace = function () { var a = arguments, o = null, i, j, d; for (i = 0; i < a.length; i = i + 1) { d = ("" + a[i]).split("."); o = YAHOO; for (j = (d[0] == "YAHOO") ? 1 : 0; j < d.length; j = j + 1) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } } return o; } 

Place it over any function that you want to place in the namespace as follows:

 YAHOO.namespace("MyNamespace.UI.Controls") MyNamespace.UI.Controls.MyClass = function(){}; MyNamespace.UI.Controls.MyClass.prototype.someFunction = function(){}; 

This method is truly standalone and can be easily adapted to your application. Just find and replace “YAHOO” with your application namespace and you will have something like MyOrg.namespace. The good thing with this method is that you can declare namespaces at any depth without having to create an object arrays between them, for example, for "UI" or "Controls"

+8
Oct 20 '10 at 1:35
source share

A short way to do what you ask is to create a "namespace" as an object literal as follows:

 var Namespace = { MyClass : (function() { ... rest of your module })(); }; 

This can lead to conflicts if you want to add other data to the namespace in other files, but you can work around this by creating a namespace first and then explicitly setting the elements.

+3
Mar 24 '10 at 0:23
source share

Design a namespace library , it is very lightweight and easy to use.

 (function(){ namespace("MyClass", MyPublic); function MyPublic(x){ return x+1; } })(); 

It also supports auto-nesting.

 namespace("MyClass.SubClass.LowerClass", ....) 

Generates the necessary hierarchy of objects if MyClass, SubClass does not exist yet.

+2
25 Oct. '10 at 19:08
source share

bob.js has good syntax for defining a JavaScript namespace:

 bob.ns.setNs('myApp.myMethods', { method1: function() { console.log('This is method 1'); }, method2: function() { console.log('This is method 2'); } }); //call method1. myApp.myMethods.method1(); //call method2. myApp.myMethods.method2(); 
+1
Nov 01 '12 at 17:39
source share
 (function($){ var Namespace = { Register : function(_Name) { var chk = false; var cob = ""; var spc = _Name.split("."); for(var i = 0; i<spc.length; i++) { if(cob!=""){cob+=".";} cob+=spc[i]; chk = this.Exists(cob); if(!chk){this.Create(cob);} } if(chk){ throw "Namespace: " + _Name + " is already defined."; } }, Create : function(_Src) { eval("window." + _Src + " = new Object();"); }, Exists : function(_Src) { eval("var NE = false; try{if(" + _Src + "){NE = true;}else{NE = false;}}catch(err){NE=false;}"); return NE; } } Namespace.Register("Campus.UI.Popup") Campus.UI.Popup=function(){ defaults={ action:'', ispartialaction:'', customcallback:'', confirmaction:'', controltoupdateid:'', width:500, title:'', onsubmit:function(id){ var popupid=id+"_popupholder"; if(this.ispartialaction){ $.ajax({ url:this.action, type:"Get", context:this, success:function(data){ $('#'+id).parents('body').find('form').append("<div id'"+popupid+"'></div>"); var ajaxContext=this; $("#"+popupid).dialog({ autoopen:false, model:true, width:this.width, title:this.title, buttons:{ "Confirm":function(){ if(ajaxContext.customcallback==''){ var popupform=$(this).find("form"); if(popupform.isValid()){ $.post(ajaxContext.confirmaction,popupform.serialize(),function(d){ if(d!='') { $.each(d.Data,function(i,j){ switch(j.Operation) { case 1: if($('#'+j.ControlClientID).is("select")) { $('#'+j.ControlClientID).val(j.Value); $('#'+j.ControlClientID).change(); } else if($('input[name="'+j.ControlClientID+'"]').length>0) { $('input[name="'+j.ControlClientID+'"][value="'+j.Value+'"]').prop("checked",true); } break; case 2: if($('#'+j.ControlClientID).is("select")) { $('#'+j.ControlClientID).append("<option selected='selected' value=\""+j.Value+"\">"+j.Text+"</option>"); } else { var len=$('input[name="'+j.ControlClientID+'"]').length; $('#'+j.ControlClientID+"list").append('<li><input type="checkbox" name="'+j.ControlClientID+'" value="'+j.Value+'" id="ae'+j.ControlClientID+len+'"/><label for "ae'+j.ControlClientID+len+'">'+j.Text+'</label>'); } break; case 0: $('#'+j.ControlClientID).val(j.Value); breakl default:break; } }); popupform.parent().dialog("destroy").remove(); $("#"+ajaxContext.controltoupdateid).change(); } }); } } else { executeByFunctionName(ajaxContext.customcallback,window,new Array()); } }, "Cancel":function(){ $(this).dialog("close"); } } }); $("#"+popupid).dialog("open"); $("#"+popupid).empty().append(data); }, error:function(e) { alert(e); } }); } else { var frm=document.createElement("form"); frm.id="CampusForm"; frm.name="CampusForm"; frm.action=this.action; frm.method="post"; var arr=$($("#"+id).closest("body").find("form")).serializeArray(); $.each(arr,function(i,j){ var hidd=document.createElement("input"); hidd.type="hidden"; hidd.name=j.name; hidd.value=j.value; frm.appendChild(hidd);}); document.appendChild(frm); frm.submit(); } } }, clicksubmit=function(){ var opts=$(this).data("CampusPopup"); opts.onsubmit($(this).attr("id")); return false; }; return { init:function(opt){ var opts=$.extend({},defaults,opt||{}); $(this).data('CampusPopup',opts); $(this).bind("click",clicksubmit); }}; }(); $.extend({CampusPopup:Campus.UI.Popup.init}); })(jQuery) 
+1
Feb 20 '14 at 4:26
source share

Automating namespace declarations in javascript is very simple, as you can see:

 var namespace = function(str, root) { var chunks = str.split('.'); if(!root) root = window; var current = root; for(var i = 0; i < chunks.length; i++) { if (!current.hasOwnProperty(chunks[i])) current[chunks[i]] = {}; current = current[chunks[i]]; } return current; }; // ----- USAGE ------ namespace('ivar.util.array'); ivar.util.array.foo = 'bar'; alert(ivar.util.array.foo); namespace('string', ivar.util); ivar.util.string.foo = 'baz'; alert(ivar.util.string.foo); 

Try: http://jsfiddle.net/stamat/Kb5xY/ Blog post: http://stamat.wordpress.com/2013/04/12/javascript-elegant-namespace-declaration/

0
Apr 12 '13 at 14:03
source share

This is the design pattern I use that allows nested namespaces, and also add to the namespace later (even from a separate JS file) so that you don't pollute the global namespace:

Example: JsFiddle

 (function ($, MyObject, undefined) { MyObject.publicFunction = function () { console.log("public"); }; var privateFunction = function () { console.log("private"); }; var privateNumber = 0; MyObject.getNumber = function () { this.publicFunction(); privateFunction(); privateNumber++; console.log(privateNumber); }; // Nested namespace MyObject.nested = MyObject.nested || {}; MyObject.nested.test = function (text) { console.log(text); }; }(jQuery, window.MyObject = window.MyObject || {})); // Try it MyObject.getNumber(); MyObject.nested.test('Nested'); 

Here's how to add to MyObject from another JavaScript file:

 (function ($, MyObject, undefined) { MyObject.newFunction = function () { console.log("Added"); }; }(jQuery, window.MyObject = window.MyObject || {})); // Pass `jQuery` to prevent conflicts and `MyObject` so it can be added to, instead of overwritten 

This resource helped me learn all about the various JS design patterns: http://addyosmani.com/resources/essentialjsdesignpatterns/book/

0
Jul 19 '13 at 5:31 on
source share



All Articles