Preferred technique for javascript namespacing

流过昼夜 提交于 2019-12-01 20:06:13

Note that you have to create all the intermediary objects before you can assign to a sub-object like that:

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

Consider writing a namespacing method, so you can unify your namespace code. For example:

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");

My preferred method is to have a single object (whose name is usually short, 2-3 characters, and all upper-case) as my namespace in which to contain all other objects.

The method shown below (which corresponds most closely with your second example) also shows how to hide any private functions:

// 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() {
         ...
     }

})();

This is the method used by a number of other JavaScript libraries, for example json2.js

I've never really felt the need to subdivide my namespaces into subnamespaces.

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 with this simple style. Don't bother with self-executing anonymous function wrappers. The one in your example doesn't actually do anything useful.

Nicola Peluchetti

Basically all three examples use the same "namespace" technique, that is, create a basic object (your namespace) and then augment it with your functions.

usually the root namespace is in capital letters:

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

Then you can add functionality to this base object in various ways. In your code you show three of them, but each of them end up with the same result, you can call this two functions:

proj.lib.layout.centreElem(elem, W, H);
proj.lib.layout. getAbsolutePosition(elem);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!