with Imagination: by Dustin Diaz

./with Imagination

A JavaScript, CSS, XHTML web log focusing on usability and accessibility by Dustin Diaz

Namespacing your JavaScript

Monday, April 24th, 2006

Perhaps a very uncommon approach to developing web applications that require JavaScript (but should be more common) is namespacing your scripts. This can be done very simple-like in a manner that is painless and nice-looking. And I know “looking-nice” should generally not be a determining factor on how your code should be written, but this indeed has some benefits as well.

Coming up with a Name

First things first, we need a name to space. If I were me (sometimes I’m not), but if I were, I would go with my own name Dustin Diaz. But of course, I’d want to abbreviate that to just DD. However since I don’t want this to be confused with Drag n’ Drop, I’ll add my middle initial which will make it DED. Now from this point on, all JavaScript for DustinDiaz.com or developed by me for others, it will live under the DED Object.

Extending the namespace

Perhaps my most favorite way of setting up an application object is to do the following steps:

  • Create the DED Object as a function literal
  • self-invoke the function
  • return my methods

This is demonstrated below:

Namespace Object example

var DED = function() {
	return {
		method_1 : function() {
			// do stuff here
		},
		method_2 : function() {
			// do stuff here
		}
	};
}();

The benefit of this structure is that due to the fact that we have a function literal, we can add private properties and methods into the function before returning an object. This can be done as follows:

adding private properties and methods

var DED = function() {
	var private_var;
	function private_method() {
		// do stuff here
	}
	return {
		method_1 : function() {
			// do stuff here
		},
		method_2 : function() {
			// do stuff here
		}
	};
}();

In this case if we were to set our private_method to return… oh I dunno, “Hello World” - then we can call that within our public methods, alert it, and indeed receive a nice little message. However one thing to note, I would argue whether or not our public methods are… public. Of course, in this simple example, they are nothing but public. But there are also “privledged methods” which have access from the outside (public) and also have access to private methods. They are indeed possible to delete and replace, but you can never get at the information to which they were trying to keep secret.

Douglas Crockford also explains a bit on this in relation to Objects and its members, and specifically using the this keyword in his article labeled private memebers in JavaScript. Hopefully the examples on this page will get you thinking of how better to organize your code, avoid conflicts with external application code, playing nice with the “other JavaScript kids,” and indeed the benefits of closures (inner functions). Have fun!

60 Responses to “Namespacing your JavaScript”

  1. fry

    I never felt the need to do this and I can’t agree that it’s nice-looking. I understand why you’d want this though.

  2. Dan Webb

    Good article. After thinking alot about it I came to the conclusion that this is just about the best way to namespace in JavaScript too. One other advantage to that way of laying out code is that you can easily include initialisation code in the function body that get evaluated as soon as the script is loaded. It’s a good place to attach your onload/DOMContentReady handlers:

    var Thing = {
    function initialise() {
    // do some stuff on load.
    }

    return {
    my_method : function() {}
    }

    window.onload = initialise;
    }

  3. Shaun Inman

    Nice thinking Dustin. I do something similar as far as name-spacing goes using the SI object but never delved into true private functions. After seeing your example, I liked the idea but not the lack of symmetry. Here’s what I propose (some reasoning first for Fry). Say I have an object that encapsulates XMLHttpRequest, it has two public methods, get() and form() that use the private request() method to handle all the object detection and correctly setting the request method (as in GET or POST). I don’t want people to use the request() method directly.

    SI.Request = function()
    {
    // private functions and properties
    var _private =
    {
    request : function(method, url, data)
    {
    // handle XHR
    }
    }

    var _public =
    {
    get : function(url)
    {
    return _private.request(’GET’, url, null);
    },
    form : function(form)
    {
    // parse form
    return _private.request(form.method, url, data);
    }
    };

    return _public;
    }();

    I like it. I just did some testing and I thought there might be issues with _public functions calling _private functions that rely on other _public functions but everything seems copacetic.

  4. Justin Perkins

    Using all caps for your namespace doesn’t really sit well with me, but that’s a pretty trivial matter.

    What exactly makes your var ‘private_var’ private? Seems like I can do this no problem:

    DED.private_var = “You’re not very private”;

  5. Shaun Inman

    Justin, that will create a new property named private_var on the DED object which isn’t the same as a private variable. Try it out.

  6. Kim Steinhaug

    Looks very interesting, though I must have forgotten some of the Javascript lessons since I can’t get any working samples out of any of the codes above.

    I have recently started to move all my functions into the :

    var myscript = {
    varname : ’something’,
    somefunction : function(){
    alert(this.varname);
    }
    };
    myscript.somefunction();

    If someone would be nice enough to add some alert() to the code snippets above and some invocation examples, like my selv explanatory example, then I can skip class and dive into it :)

  7. Kim Steinhaug

    By the way, your blog messes up the Javascript code, single quotes are replaced with those fancy webquotes which doesn’t exactly work in Javascript. Most people probably knows this, but the cut’n'paste people should know this as they will get a Javascript error.

  8. Frank Manno

    Hey Dustin!

    Quick question… Would you recommend this only for classes you don’t wish to have instantiated (ie: static class)?

    One thing I’ve learned recently is that when encapsulating any methods of a class within the constructor function, any object instances of that class will each have their own copy of the methods, rather than sharing a copy from the prototype object; thus using more memory.

    I noticed the method you mentioned is being used in the YUI libraries (kickass, btw!)… Can you shed any light on whether or not this is true for the namespacing technique here?

    Thanks!
    Frank

  9. Dan Webb

    This technique creates a namespace rather than a ‘class’ that can have multiple instances. Be careful not to confuse them. You can put object constructors inside your namespaces though:

    var animals = (function() {

    function Dog(name) {
    this.name = name;
    }
    Dog.prototype.bark = function() { alert(”Woof! ” + this.name) }

    return {
    Dog : Dog;
    }
    })();

    Then you can make lots of dogs like this:

    var fido = new animals.Dog(’fido’);
    fido.bark() //=> alerts ‘Woof! fido’

    var rover = new animals.Dog(’rover’);
    rover.bark(); //=> alerts ‘Woof! rover’

  10. Justin Perkins

    Shaun,
    Sure enough :)
    I did try it out before, but it didn’t occur to me that I was creating a new variable not setting the existing one. How wacky.

  11. Frank Manno

    Dan,

    Ahh!! That makes sense. I totally confused myself with the namespace/class difference. I’ve been burying myself with as much OO-related JS content these past few weeks, that I seem to automatically swerve to that end of the curve. ;)

    Your example makes total sense. Thank you!

    One question about the example though… The anonymous function that you declared at the beginning of the “animals” namespace; what is the purpose of that? Is it called at any point, or does it serve some other purpose?

    Another thing I noticed (not sure if it was just a typo on your part), was that having a semi-colon in the return:

    return { Dog : Dog; }

    seems to throw an error. Removing it works. Not sure why, but it does.

    Thanks again for the clarification!

  12. Dan Webb

    That anonymous function encloses the entire namespace as in Dustin’s example. As for the ; that was meant for the line below (oops) but removing it is fine.

  13. Dustin Diaz

    I really need to come up with a better system for people to post code on this blog. I realize with as much as I talk about it, people are definitely going to post it.

    As regards to Justin’s comment on “What makes them private” - they indeed cannot be called from outside the DED Object. For instance, in this case, you can’t call DED.private_method(). However the other methods (in the return) can. That’s why I think it’s best to call them those ones ‘privledged’.

  14. Dustin Diaz

    Dan, you also beat me to the true OO example. I was going to post something similar last night but got too sleepy. I may just have to single you out on a later entry.

  15. Dan Webb

    single me out? That sounds scary…

  16. Dustin Diaz

    Hehe. It will be completely in a good way. Basically you’ve demonstrated how to use function literals (or object literals) and make them reusable like classes.

  17. Brad Fults

    Another site detailing OOP in JS. It’s more digestible than Crockford’s for me at least.

  18. fry

    I’ve seen another attempt at ‘namespacing’ in FlashObject on deconcept. In version 1.3 he even went as far as “com.deconcept.*”. If you really want to go all the way with namespacing you should probably use both of them combined. What if somebody wanted to add animals.Cat to Dan’s example?

    As a way of cleanly adding private members I do agree this is a good techinque. But you have to remember that private methods in javascript are not really private since anybody can see them in the code and can change the script to make them public. It forces people to use the API instead of the core, but still…

  19. Dustin Diaz

    Fry, you may be mistaken by what a private method is. Just because you can see it doesn’t mean it’s public. If we were to go by that definition, then PHP is an entirely hidden language just because we can’t see the source code. Read Crockfords article and you might have a better understanding on why they’re called private.

    Also, the com.domainName is a technique used in Java - or so says Jonathan Snook who told me so.

    Another point on Justin’s comment about all capitals on ‘DED’ - since JavaScript is case-sensitive when declaring variables, it is less likely that the ‘DED’ namespace will have a collision with another.

  20. Dustin Diaz

    Just one thing to note though on Fry’s comment again, the deconcept method is indeed a good approach. But although at first pass it seems like a bullet-proof approach, it requires everyone to be on board with it. Declaring variables like ‘com’, ‘net’, or ‘eu’ seem very likely to be collided with. But then again, so can ‘DED’. Nevertheless, nothing really is full proof and requires attention to detail when you’re integrating code from multiple applications and developers.

  21. Justin Perkins

    > the com.domainName is a technique used in Java

    I think this is more an API/SOAP/SOA thing, not exactly Java specific. .NET uses the same syntax to when creating namespaces for webservices.

    > it is less likely that the ‘DED’ namespace will have a collision with another.

    Yeah I was just saying that b/c it looks like a constant. Of course, an acronym isn’t a constant though. Nevermind, I’m just being a pedantic nut.

  22. fry

    Dustin, I know what you’re saying about private methods and what the difference is (I am a JavaScript and Java user/developer). My point was that when using a javascript library I can just copy/paste the code around to make a method public. With compiled languages you can’t…

    I don’t think that there are many people who use private methods in JavaScript and I rarely see a private method that has a valid reason to be private (why shouldn’t a power user use the request method from Shaun’s example?).

  23. Mark Wubben

    There are two great articles on this subject by Tom Trenka: Coding for Portability 1 and Coding for Portability 2.

  24. philmccluskey.com codestream » Blog Archive » Links for Monday 29 May 2006

    [...] Namespacing your Javascript. [...]

  25. Jonathan Aquino

    Dustin - Have you checked out the Dojo toolkit? It has a great namespacing feature. You just do:

    dojo.provide(’com.dustindiaz.tetris.ScorePanel’);

    Then later you can import it using:

    dojo.require(’com.dustindiaz.tetris.ScorePanel’);

  26. Web Femme

    Dustin,
    Have you seen Ajile [http://ajile.sf.net/]? It’s a very effective approach to JavaScript namespaces with most of the end-user complexity removed.

    Ajile lets you do define a namespace as simply as:

    Namespace (”com.dustindiaz”);

    and then import from it as easy as:

    Import (”com.dustindiaz.MyObject”);

    or

    ImportAs (”MyAlias”, “com.dustindiaz.MyObject”);

    It’s really worth a look.

  27. How to achieve private, public, and privileged members in JavaScript

    [...] Granted, I’ve written on this topic briefly when talking about JavaScript namespaces but didn’t get into full detail on how to achieve all three styles, and how it all actually works. [...]

  28. Vitamin Features » The Importance of Maintainable JavaScript

    [...] This step ties in with unobtrusive JavaScript, so let’s not dwell on it. In essence it means that a maintainer could add your script to any page and don’t risk overwriting other code by doing so. You can keep scripts self-contained by namespacing them or wrapping them in an object via the object literal. You ensure you don’t hijack variables by keeping them in scope of your functions via the var keyword and you don’t hijack events by using addEvent()code> or its derivates. [...]

  29. anotherLoser

    i suppose this is namespacing as javascript allows it, but i am not sure i would classify it as such with regards to traditional language semantics, particularly with regards to scoping rules and their verification (for classes as well as objects). this is simply the semantics of functions in javascript, and your ‘namespace’ is just a viable retval. why not then just refer to this as what it is - a function?

  30. Henrik Gemal

    I’m using your approach for creating namespaces but run into a problem.

    I need a way to return an object.

    I have the BLA namespace with some functions in it.

    Now I need to add a cookie object to the BLA namespace but people need to call it like this:

    new x = BLA.cookie();
    x.set(”test”, “value”);
    x.get(”test”);

    Is there a way to create such an object using your approach?

    BLA.cookie = function() {
    return {
    new Object();
    }
    }();

    the above doesn’t work but would it be possible to to something like that?

  31. Bradley Mazurek

    Late to the party, but….

    Desparately wanting namespacing to give some organization to my code, I tried the following and was generally pleased with the result, but did have a couple of questions.

    I was able to use this for nested namespaces. I would create the namespace as an empty object in the parent namespace, then redefine it later to be a namespace created in the same form as you describe. Is there an easier way?

    Finally, I had some difficulty referring to public members from private methods and referring to public members from other public members. It turns out I needed to fully qualify the names. Is there an easier way?

    Thanks,
    Brad

  32. Brad's Helper

    Brad,
    You might want to look at: http://ajile.iskitz.com/

    Ajile is a JavaScript namespacing library with importing.

    Good luck.

  33. Gianni Milanesi’s Weblog » Blog Archive » JavaScript-Fu: Guidelines for Web 2.0 Mastery

    [...] Namespacing in its essence is the art of clearly seeing your code as one being. Namespacing is the path to prevent clashing of variable and function names in the jungle of scripts, and is one of the points of the JavaScript-Fu Star of Unobtrusiveness.The way of the Namespace is simple and clear once you learn to understand its true meaning. The following mantra can help you better understand the path you have to follow to reach the Namespace nirvana through the use of Object Literal Namespacing: [...]

  34. Ali

    It’s nice, i didn’t know that it’s possible to define a function in another function in javascript.

    Anyway it’s a great method when you have 2 function with the same name in a page, just like what you do in common programming language like JAVA.

  35. Fred

    I don’t think that there are many people who use private methods in JavaScript and I rarely see a private method that has a valid reason to be private (why shouldn’t a power user use the request method from Shaun’s example?).

    A power user can modify the script if it seems necessary. Encapsulation’s purpose is not to hide source or render it untouchable. It merely helps enforce integrity. By making members private, the developer is saying, “This is intended for internal use. If you mess with it, the data or functionality may become untrustworthy.” That’s why I use encapsulation in my own projects, even when I’m the only developer who will ever touch the code. It can keep you from shooting yourself in the foot.

  36. Fred

    Incidentally, I was playing around with this concept and found a syntax for namespacing that I consider a little more readable:

    var NAMESPACE = new function() {

      // Private stuff
      var private_variable = ‘foo’;
      function private_function() { alert(’private’); }

      // Public stuff
      return {
        public_variable: ‘bar’,
        public_function: function() { alert(’public’); }
      };

    }

    I like it because the “new function()” in the NAMESPACE declaration is an immediate indication that the contained code is a single instance of the object.

  37. Miketrix

    Could I ask a beginner question…

    I’m developping a suite of controls in ASP.Net and I’m trying to figure out how I could code the client side script (js) the best way… using JS inheritance for all my controls…

    As example, let’s say I have following server-side controls (coded in c#):

    MyTextBox -> provides some extra client side functionalities using js (like watermarking)

    MyMaskedTextBox -> inherits from MyTextBox (and from its watermark functionality) but adds masking capability. In c#, no problem to inherit the MyTextBox class, it’s common practice. But in JS, how can this be done using the best practices… And also not using some special features (i need it to work on almost any common browser)…

    And so I would create MyOtherTextBox, inheriting from MyTextBox too…

    The problem here does nothing to do with C# coding, I just want to learn how I could achieve a better object oriented implementation for my components at client side.

    So my questions are :

    - What would you advice in order to create some clean javascript objects ?
    - I first though it would be nice to wrap all my objects (MyTextBox, MyMaskedTextBox, …) in a single namespace, but does it really matter in Javascript ? It disturbs me because the syntax to define a Namespace I can read here seems to be quite the same as I would define an Object. For example :

    var NAMESPACE = new function() {

    // Private stuff
    var private_variable = ‘foo’;
    function private_function() { alert(’private’); }

    // Public stuff
    return {
    public_variable: ‘bar’,
    public_function: function() { alert(’public’); }
    };

    }

    If i replace the word NAMESPACE by MYOBJECT, wouldn’t it be like a new object definition ? (I’m not familiar with JS OO syntax so if i’m wrong plz tell me ;o) )

    Well, I have many questions to ask, I anybody could give me some answers, I really would appreciate. Actually, I could make it by myself, the way I think, but I really want to improve my practices in JS and JS OO so … I hope that you guys will make me a better JS coder :-)

    Thanks by advance !

    Mike.

  38. Peter Foti

    JavaScript inheritance… Here’s a quick example. SubClass inherits the properties of it’s prototype, so you just overwrite the default prototype (Object) with your SuperClass:

    
    
    function SuperClass( className )
    {
        this.className = className;
        this.creationDate = new Date();
    }
    
    function SubClass()
    {
        this.foo = "bar";
    }
    SubClass.prototype = new SuperClass( "SubClass" );
    
    var Example = new SubClass();
    var str = Example.className + "\nCreated: " + Example.creationDate + "\nfoo: " + Example.foo;
    alert(str);
    
    
  39. Stefan

    In JavaScript2.0 there are already built in language approaches for javascript solving the name space problem.

  40. Peter Foti

    I forgot to mention… the YUI Library also provides a mechanism for extending classes:

    http://developer.yahoo.com/yui/yahoo/#extend

  41. Miketrix

    Ok, thanks for the first answers.

    So some quick questions:

    - speaking about prototype, its a word used on every post speaking about Javascript. Sorry for asking that but is there any relation between Peter Foti example and the Prototype library ? I think there isn’t, but it’s just to make it sure. Is “prototype” a reserved word in STANDARD Javascript or does it need the prototype library to get working ?

    What I need is to implement an independant (and cross browser) solution (at least, IE and FF) so I don’t want to use external functionalities (like prototype, moofx and others…)

    Talking about Javascript 2.0, is it compatible in all browsers ? (even older ones ?)

    Thank you for your help !

    Mike.

  42. Peter Foti

    @Miketrix
    Just to clarify, yes “prototype” (in the way I used it above) is built into JavaScript and should not be confused with the Prototype JavaScript Framework (which I personally think was a very stupid naming choice as it only causes confusion). You do NOT need the Prototype Framework stuff for my examples.

    Why do you need to implement a totally independant solution? I highly recommend the YUI Library. It has a BSD license. It’s VERY well put together, with a growing user base and a great support mailing list. It works in A-Grade browsers (http://developer.yahoo.com/yui/articles/gbs/gbs_browser-chart.html), and makes development SOOOO much easier. Don’t reinvent the wheel.

  43. Miketrix

    Hi Peter and thank you so much for your answoer.

    Now I won’t be confused anymore on prototype.

    Actually, I’m developping some customized controls in C# for ASP.Net 1.1 (kind of enhanced input controls… Sure I’m not the first to do that). Those are developped for many reasons.
    The first is that we need them in our financial software, and therefore we don’t want to use external libraries… Well it’s more that our chiefs don’t agree on using external stuff … I know it’s not always a good choice but … anyway. Furthermore, our software must run on older IE versions too. I’m not targetting only IE for my controls, but at least I need to try to make them the more compliant I can.

    The second reason why I’m asking about Javascript Practices is that I want to improve my knowledge and abilities in JS development. Actually, I know like most developers how to code functions in Javascript, getting hand on the DOM in order to make some common features (collapse/expand, validation of input fields, text/image hover effects…) but what I’m interested in, is to achieve using Javascript as a “truly” OO language… Getting benefits of inheritance, encapsulation, …

    The first controls I’m developping for the moment are quite simple :
    - TextBox : providing Watermark functionality
    - NumericBox (inherits from TextBox) : providing real-time numeric typing, including currency symbol, group and decimal separator, …
    - MaskedBox (inherits from TextBox) : providing mask support (for ex: 999-999999-99)
    - DatePicker (inherits from MaskedBox) : providing dynamic calendar popup + date input field.

    As you can see, all components I have are in a same hierarchy. Of course, many logic and validations are done at server side (in C#) and all Javascript is included dynamically in the page also using Javascript.

    But instead of declaring a bunch of Javascript Functions, passing tons of parameters to each function, I would prefer to declare a clean object for each control to handle. SO the object can handle itself, calling methods that get access to the properties of the object, without the need of passing them again and again… And also, some methods of TextBox control could be overrided for other controls inheriting from it.

    Well, not much more to say, I just want to use OO as far as possible in common Javascript programming.

    SO, any extra advices are still welcome.

    Thanks again !

  44. Peter Foti

    @Miketrix
    Your approach is a sound one. I, too, prefer an OO methodology. I like to think of it like this:

    1. The Content should be accessible for the widest audience possible. That means not reliant on JavaScript or CSS.
    2. Additional behaviors (via JavaScript) should be unobtrusive, and get “attached” to the content.

    For example, I prefer to define my JavaScript objects and then “attach” whatever event handlers (vs. defining intrinsic event handlers using onclick attributes, etc.). Sometimes scoping issues can be a little tricky, but once you get the hang of it I’m sure you’ll find it’s a much “cleaner” way to work.

    therefore we don’t want to use external libraries… Well it’s more that our chiefs don’t agree on using external stuff

    Understandable I suppose. But one could argue that the YUI Library is more of a Framework with which to build your application. The methods it exposes (particularly in the Dom and Event Utilities) can greatly increase productivity.

    Also, I think it will be difficult to create JavaScript that is 100% compatible with new and ancient browsers. You’ll probably want to find some good references that discuss exactly what versions of JavaScript are supported by each browser version, along with something that defines when a method was added to JavaScript (for example, the String.substr() method became available in JavaScript 1.2, which was around the time of Netscape 4 and IE 4). You might be better off to define a minimum browser requirement.

    Good luck.

  45. Fred

    @Miketrix: Regarding your question about namespaces in JavaScript:

    If i replace the word NAMESPACE by MYOBJECT, wouldn’t it be like a new object definition ? (I’m not familiar with JS OO syntax so if i’m wrong plz tell me ;o) )

    In the example I provided, NAMESPACE would be a single instance of an object. “var NAMESPACE = new function() {}” creates an anonymous constructor and instantiates the object immediately. NAMESPACE is therefore the object itself. The constructor is no longer available. In that respect, its usage is comparable to the singleton design pattern.

    
    var Namespace = new function() {
        var foo = "Private variable foo";
        return {
            bar: "Public variable bar",
            show_foo: function() {
                alert(foo);
            },
            show_bar: function() {
                alert(bar);
            }
        };
    }
    
    Namespace.show_foo();
    Namespace.show_bar();
    
    MyObject = new Namespace();  // This won't work because Namespace is not a constructor
    

    Just thought I’d clarify how it works to avoid confusion.

  46. Fred

    Oops… there was a bug in my previous example. The bar variable isn’t available to the show_bar() function. That’ll teach me to post code without running it in a browser first. Here’s a working version.

    
    var Namespace = new function() {
        var foo = "Private variable foo";
        return {
            bar: "Public variable bar",
            show_foo: function() {
                alert(foo);
            }
        };
    }
    
    Namespace.show_foo();
    alert(Namespace.bar);
    MyObject = new Namespace();  // This won't work because Namespace is not a constructor
    
  47. Kris Zyp

    Regarding the question about JS2.0, it is not in old browsers, it is not even in new browsers. The lastest new version of JS coming to us is 1.7 (with generators and destructuring) in Firefox 2.0. And even that is along way from being widely used enough for using in public web pages (it will surely be a while before IE implements it).

  48. All in a days work…

    [...] Namespacing your JavaScript Create the DED Object as a function literal, self-invoke the function, return my methods. Now, we can add private properties and methods into the function before returning an object. [...]

  49. Svein Are

    What if I want to create namespace of the variant “com.mycomp.section” instead of just DED. I guess it’s not this simple:

    
    var com.mycomp.section = function() {
    	return {
    		method_1 : function() {
    			// do stuff here
    		},
    		method_2 : function() {
    			// do stuff here
    		}
    	};
    }();
    

    Any hints?

    Also, we use YUI as our main library. But I guess using YAHOO.namespace() is mostly for extentions for the YUI lib. Or is it a good choise for all our functions?

    
    YAHOO.namespace ("com.mycomp.section");
    YAHOO.com.mycomp.section.Method = function(info) {
        alert(info);
    };
    

    What do you think?

  50. Dustin Diaz

    YAHOO.namespace() is good for all your library methods. But it still essentially extends everything from the YAHOO object… which I don’t see as all that necessarily bad. In the end, if for instance I had DED.util.Dom… You can’t directly extend all the way out to ‘Dom’ using var.. Eg:

    var DED.util.Dom = function() {
    
    };

    In this case, ‘DED’ needs to be declared before it’s extended, and same with ‘util’. So here’s a few that would work:

    var DED = {
        util : {
            Dom : {
                // put Dom stuff here...
            }
        }
    };

    The above example might not be preferred, but it works. I would do something more like the following:

    var DED = {
        util : { },
        widget : { },
        example : { }
    };
    DED.util.Dom = function() {
        // Dom stuff here
    };

    There are of course other favorable ways too.

  51. Rapid Shot

    @Svein Are

    You should take a look at Ajile (http://ajile.iskitz.com/). Lets you create the kind of custom namespace you’re talking about without it being nested under something like YAHOO.

    Using it you can do:

    Namespace(”com.mycomp.section”);

    com.mycomp.section.Method = function(info) {
    alert(info);
    };

    Pretty nifty I’d say…

  52. Templaterie Blog

    [...] Nachtrag: Scripts schreiben, die mit andern Scripts gut können durch Namespacing: Namespacing your JavaScript, sprich Namen wo es geht privat lassen und global schreiben, ihnen sozusagen einen eigenen Raum geben. [...]

  53. Jared Christensen

    Great site, I love the content. I hate to complain but any chance you could change the type or background color? It is a bit hard on my eyes to read. The black type is a bit strong on the white background. Try #333333 for the type. With the black background the white type is also too strong. Thanks for all the great coding tips.

  54. Stuart

    OK, I’ve read this article about ten times since you published it. I think I’m finally getting it. I’m a real fast learner. I’m trying to apply this method to an existing class (Grid.js) that I use that manipulates some table (DOM) properties. I had it set up that the class was used on all pages that contained a certain table. I then had some prototype methods in a separate file that I only used on a specific few of those pages. I’m kinda stuck now because Grid.prototype.someMethod = function () {…} isn’t going to work. I want to be able to exclude the protoype methods on pages that don’t require them in order to keep file size down. Is it possible to have prototype methods outside the object literal?

    Thanks

  55. Dan

    I’ m also very interested in any answers could be given to Stuart’s problem

    Prototyping of the closure is assumed as working in Dustin’s book (pag 36) but, as far as I can see, it doesn’t

  56. Ezrad

    If that code isnt sexy to you then you need some viagra. Im currently rewritting a library and I’ve been griping with whether or not I should. I finally think I will, might as well. i want to be a cool kid too!

  57. Aaron

    See JavaScript: The Definitive Guide 5th Edition by David Flanagan Chapter 10: “Modules & Namespaces” for an excellent (but advanced) discussion on the matter.

  58. kenITR

    Could someone please, please, please post a working example of Dustin’s routine? Preferably one where you pass something in, transform it and pass it out.

    Thanks very much.

    Ken

  59. Lachlan McDonald

    In regards to using the Yahoo namespacing, as mentioned by Dustin Diaz and Svein Are; I’d prefer to keep my own code as fairly unrelated to the Yahoo methods as possible. Of course, its just a matter of personal taste really, but I like to think of my code as a separate entity to any of the libraries I employ.

  60. The Importance of Maintainable JavaScript | Net Feast

    [...] page and don’t risk overwriting other code by doing so. You can keep scripts self-contained by namespacing them or wrapping them in an object via the object literal. You ensure you don’t hijack variables [...]

Get "JavaScript Design Patterns"

"As a web developer, you'll already know that JavaScript™ is a powerful language, allowing you to add an impressive array of dynamic functionality to otherwise static web sites. But there is more power waiting to be unlocked--JavaScript is capable of full object-oriented capabilities, and by applying OOP principles, best practices, and design patterns to your code, you can make it more powerful, more efficient, and easier to work with alone or as part of a team."

Buy JS Design Patterns from Amazon.com Buy JS Design Patterns from Apress

All content copyright © 2003 - 2009 under the Creative Commons License.

Archives | Blog Search