namespaces - Preferred technique for javascript namespacing -


my code going turn mess if don't start using sort of namespacing technique. i'm relatively new programming large javascript projects have significant experience systems programming in c++/java/python etc.

basically i'm trying identify preferred method creating javascript namespaces, , pros/cons each method.

for example use either of following 3 methods:

var proj.lib.layout = {   "centreelem":        function (elem, w, h){    },    "getabsoluteposition":   function (elem){    } }; 

or

var proj.lib.layout = {}; (function(){   var l = proj.lib.layout;    l.centreelem = function (elem, winw, winh){     ..   }    l.getabsoluteposition = function (elem){     ..   } })(); 

or

var proj.lib.layout = new function(){   function centreelem(elem, w, h){     ..   }    function getabsoluteposition(elem){     ..   }    this.centreelem          = centreelem;   this.getabsoluteposition = getabsoluteposition; } (); 

there other ways obviously, these first i've seen , thought of. can there "best" technique, or @ least point me towards pros/cons can evaluate best me?

note have create intermediary objects before can assign sub-object that:

window.one.two.three = {}; // fails window.one = { two: { three: {} } }; 

consider writing namespacing method, can unify namespace code. example:

window.proj = {}; // n - {string} - string representing namespace create on proj // returns object can assign values window.proj.namespace = function(n) { /* ... */ };  (function(ns) {     ns.mymethod = function() {};     ns.myothermethod = function() {};     ns.myproperty = "foo"; })(proj.namespace('lib.layout'));  assert(proj.lib.layout.myproperty === "foo"); 

Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -