Addition of a global namespace function?

Mark A. Ziesemer online at
Tue Dec 1 15:08:15 PST 2009

I'd like to propose a "namespace()" function to the base ECMAScript
language.  (I previously thought about this only in terms of
JavaScript, but I'm guessing it really belongs in ECMAScript?)

I've previously blogged about this at
, having actually become part of the review process for Firefox
add-ons, being linked to from .

While it is easy enough to define and use such a namespace function
without it being included in the base language, the same could be said
for the new String.trim functions that were just recently added.  I
further feel that it would be very beneficial to have a "namespace"
function declared in a standard rather than being used in an ad-hoc
fashion, as this would hopefully discourage others from declaring a
global "namespace" function that is unrelated or otherwise
incompatible.  Finally, I think that this would be an important
addition, especially with the amount of JavaScript being combined into
web pages today.  (I could come up with many more reasons, but I think
this is a pretty good summary to start with.)

I understand that at best, this would probably not appear until a
later version of the specification.  In the meantime, it could
continue to be supported as a back-portable extension, such as the
Array extras.  However, most importantly, it would define this as part
of the (future) "language standard".

Here is the actual function I am proposing, just so you don't have to
click through:

var namespace = function(name, separator, container){
  var ns = name.split(separator || '.'),
    o = container || window,
  for(i = 0, len = ns.length; i < len; i++){
    o = o[ns[i]] = o[ns[i]] || {};
  return o;

Example of use:

com.example.namespace.test = function(){
 alert("In namespaced function.");

Or, as one statement:

namespace("com.example.namespace").test = function(){
 alert("In namespaced function.");

Either is then executed as:


Thanks for your consideration.

Mark A. Ziesemer

More information about the es-discuss mailing list