JavaScript – Namespace Function

One thing that most JavaScript writers do now, which is a good practice, is they create namespaces for their functions and variables. The following is a definition for a function that can be used to easily create namespaces of any depth:

namespace = (function(global) {
  return function() {
    for(var ns, obj, arr, j, i = 0; arr = arguments[i++];) {
      for(obj = global, arr = arr.split("."), j = 0; ns = arr[j++]; obj = obj[ns]) {
        if(obj[ns] == null) {
          obj[ns] = {};
        }
      }
    }
  };
})(this);

I have to admit, this idea is not originally mine (it came from here), but the code is. The following is an example use of this handy function:

namespace("jPaq.Event", "jPaq.Color");

Who knows, this simple, yet powerful function may appear in the next version of jPaq! 8)

Leave a Reply

Your email address will not be published. Required fields are marked *


7 − = three

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>