Preferred technique for javascript namespace

My code will become a mess if I don’t start using some kind of namespace technique. I am relatively new to programming large javascript projects, but have significant experience with system programming in C ++ / java / python, etc.

Basically, I am trying to determine which one is preferable for creating javascript namespaces, as well as what are the pros / cons for each method.

For example, I could use one of the following three 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 are other ways to make this too obvious, but these were the first ones that I saw and thought. Can anyone say that there is a β€œbest” technique, or at least point me to some pros and cons, from which I can evaluate what is best for me?

+4
4

, , :

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

namespacing, . :

window.proj = {};
// n - {String} - A string representing a namespace to create on proj
// returns an object you can assign values to
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");
+3

, ( , 2-3 ) , .

, ( ), , :

// In this example the namespace is "QP"
if (!QP) {
    var QP = {};
};

// Define all objects inside an closure to allow "private" functions
(function() {

     QP.examplePublicFunction = function() {
         ...
     }

     function examplePrivateFunction() {
         ...
     }

})();

, JavaScript, json2.js

.

+1

, " ", ( ), .

:

if (typeof (MYAPP) == "undefined" || !MYAPP) {
    var MYAPP= {}
};

. , , :

proj.lib.layout.centreElem(elem, W, H);
proj.lib.layout. getAbsolutePosition(elem);
0

The Google Closure Javascript library uses this style (which is not exactly like any of your examples)

goog.math.clamp = function(value, min, max) {
  return Math.min(Math.max(value, min), max);
};

I would stick to this simple style. Don't worry about self-learning anonymous wrappers of functions. The one in your example actually does nothing useful.

0
source

All Articles