1069

How do I create a namespace in JavaScript so that my objects and functions aren't overwritten by other same-named objects and functions? I've used the following:

if (Foo == null || typeof(Foo) != "object") { var Foo = new Object();}

Is there a more elegant or succinct way of doing this?

George Stocker
  • 57,289
  • 29
  • 176
  • 237
Scott McKenzie
  • 16,052
  • 8
  • 45
  • 70
  • 21
    I can see where you're going with the checking to see if the namespace is taken, but since the object will not be created if this fails I think the better approach is to alert if the namespace is taken. Frankly this should just not happen in most JS situations and should be caught quickly in development. – annakata May 19 '09 at 08:54
  • 19
    Take a top-level "namespace" (window property). Own it. Conflicts should be detected early on in testing. Don't bother adding all these "what if" checks. *It's a fatal issue for duplicate "namespaces" and should be treated as such*. You can follow an approach like jQuery to allow inhabiting a custom "namespace"; but this is *still* a design-time issue. –  Jul 04 '10 at 04:33
  • see also http://stackoverflow.com/questions/2102591/namespacing-technique-in-javascript-recommended-performant-issues-to-be-aware for performance issues – Tim Abell Jun 15 '12 at 11:37
  • see also http://stackoverflow.com/questions/4125479/whats-the-difference-between-using-objects-and-functions-for-namespacing-in-jav for object vs function namespaces – Tim Abell Jun 15 '12 at 13:11
  • This is a ton of information, but really lays out the differences amongst the different JS design patterns. It helped me a lot: http://addyosmani.com/resources/essentialjsdesignpatterns/book/ – Justin Jul 19 '13 at 05:12
  • 1
    Meh, nowadays we have symbols and modules, so duplicate namespaces shouldn’t even be an issue. – Sebastian Simon Jul 04 '21 at 18:10

29 Answers29

1073

I use the approach found on the Enterprise jQuery site:

Here is their example showing how to declare private & public properties and functions. Everything is done as a self-executing anonymous function.

(function( skillet, $, undefined ) {
    //Private Property
    var isHot = true;

    //Public Property
    skillet.ingredient = "Bacon Strips";

    //Public Method
    skillet.fry = function() {
        var oliveOil;

        addItem( "\t\n Butter \n\t" );
        addItem( oliveOil );
        console.log( "Frying " + skillet.ingredient );
    };

    //Private Method
    function addItem( item ) {
        if ( item !== undefined ) {
            console.log( "Adding " + $.trim(item) );
        }
    }
}( window.skillet = window.skillet || {}, jQuery ));

So if you want to access one of the public members you would just go skillet.fry() or skillet.ingredients.

What's really cool is that you can now extend the namespace using the exact same syntax.

//Adding new Functionality to the skillet
(function( skillet, $, undefined ) {
    //Private Property
    var amountOfGrease = "1 Cup";

    //Public Method
    skillet.toString = function() {
        console.log( skillet.quantity + " " +
                     skillet.ingredient + " & " +
                     amountOfGrease + " of Grease" );
        console.log( isHot ? "Hot" : "Cold" );
    };
}( window.skillet = window.skillet || {}, jQuery ));

The third undefined argument

The third, undefined argument is the source of the variable of value undefined. I'm not sure if it's still relevant today, but while working with older browsers / JavaScript standards (ecmascript 5, javascript < 1.8.5 ~ firefox 4), the global-scope variable undefined is writable, so anyone could rewrite its value. The third argument (when not passed a value) creates a variable named undefined which is scoped to the namespace/function. Because no value was passed when you created the name space, it defaults to the value undefined.

j08691
  • 204,283
  • 31
  • 260
  • 272
Jaco Pretorius
  • 24,380
  • 11
  • 62
  • 94
  • 10
    +1 for this great sample. For anyone interested, this sample was part of Elijah Manor's excellent presentation at Mix 2011 (ignore the title) http://live.visitmix.com/MIX11/Sessions/Speaker/Elijah-Manor – Darren Lewis Sep 12 '11 at 21:01
  • 13
    From Elijah's article, here are the pros and cons of this approach, paraphrased. Pros: 1. Public and private properties and methods, 2. doesn’t use cumbersome OLN, 3. Protects undefined 4. Ensures that $ refers to jQuery, 5. Namespace can span files, Cons: Harder to understand than OLN – Jared Beck Oct 14 '11 at 00:47
  • Excellent. But it fails if jQuery is not already loaded. Is there a way to execute anyway, and in there to test for it and load if necessary? – Antoine Jan 11 '12 at 12:36
  • 1
    @Antoine - Why would it fail? jQuery should be the dependency and should be loaded preceeding your script – Ryan Feb 08 '12 at 03:38
  • 1
    @Ryan: I'm calling this from a bookmarklet where I don't test for jQuery (want to keep the bookmarklet as simple as possible, logic is done server-side). I overcame this by removing the $ parameter, and testing/loading for jQuery inside the namespace. – Antoine Feb 08 '12 at 08:58
  • 6
    This is called today **IIFE** (_Immediately Invoked Function Expression_). Thanks for your answer +1! – Gustavo Gondim Feb 25 '13 at 19:36
  • 1
    @CpILL the third ùndefined` argument is for ensure that no else function will pass a third argument and will modify the behavior. It is a guaranty. – Gustavo Gondim Feb 25 '13 at 19:40
  • 23
    @CpILL: not sure if still relevant, but the third, `undefined` argument is source of the variable of value `undefined`. While working with older browsers / javascript standard (ecmascript 5, javascript < 1.8.5 ~ firefox 4), the global-scope variable `undefined` is writable, so anyone could rewrite its value. Adding third, additional argument you are not passing makes it value `undefined`, so you were creating namespace-scope `undefined` which won't be rewritten by outside sources. – mrówa May 22 '13 at 11:29
  • So I don't really understand the purpose of window.skillet = window.skillet || {}. Why would you want another file to accidentally append to the definition of skillet? Wouldn't you rather it did so intentionally? I'd rather see a big bug pop up.... Perhaps it's for when people want to add extensions to your module but you don't know which one is loading first? – SapphireSun Jul 03 '13 at 00:10
  • 2
    @SapphireSun: Who said it had to be by accident? The syntax allows you to extend the class in multiple places. – Jay Sullivan Jul 24 '13 at 13:46
  • If you feel confused, @Jared Beck presented an excellent pro/con breakdown of the article. Perhaps one additional Con: Don't use this just because it's better. The { } OLN (Object Literal Notation) as explained in the accepted answer is perfect for simple scenarios. – Laoujin Aug 13 '13 at 17:58
  • 8
    @SapphireSun The benefit of `window.skillet = window.skillet || {}` is that it permits multiple scripts to safely add to the same namespace when they don't know in advance in what order they will execute. This can be helpful either if you want to be able to reorder your script inclusions arbitrarily without breaking your code, or if you want to load scripts asynchronously with [the async attribute](https://developer.mozilla.org/en/docs/Web/HTML/Element/script) and so have no guarantee about execution order. See http://stackoverflow.com/questions/6439579/what-does-var-foo-foo-mean-in-javascript – Mark Amery Jun 26 '14 at 21:37
  • I was going to add an example as well; I commend you on this example code. @MarkAmery, I have to say that your comment is probably one of the most misunderstood components of javascript structures and you have provided an excellent explanation showing the scope of each function/variable and how to invoke them. – Anthony Mason Sep 02 '14 at 16:22
  • There is one more big downside (imho) with doing `namespace.func = function(){ /* ... */};`: All these functions end up being **anonymous**. It is an inconvenience when debugging, looking at stacktraces etc. Please consider to [stop writing anonymous functions](http://stijndewitt.com/2013/12/02/stop-writing-anonymous-functions/). (I am the author of that blog post). – Stijn de Witt Jan 06 '16 at 23:05
  • 2
    The answer provided in this example has a bug - I can't find a solution for this. In the original implementation of `skillet`, a private variable `isHot` is declared. Subsequently, `skillet` is extended to add the `toString()` method, and in this extension the private variable `toHot` is referenced. In my tests, this is not possible, as the private variable from the *original* implementation can't be referenced in a subsequent extension. Paste the code from this answer into the JS console in your browser. `skillet.toString()` fails: **ReferenceError: Can't find variable: isHot** – daveruinseverything Apr 18 '17 at 00:43
  • @daveruinseverything The full example on the site referenced in the answer shows that causes an error. The benefit is you can create a second closure? to extend the namespace but the closures still can't access the private variables of the other, but that also means you don't have to worry about your private variables conflicting with those in the other. (I'm just starting to understand this, so may have some of that wrong.) – aamarks May 22 '18 at 19:54
814

I like this:

var yourNamespace = {

    foo: function() {
    },

    bar: function() {
    }
};

...

yourNamespace.foo();
user229044
  • 232,980
  • 40
  • 330
  • 338
dfa
  • 114,442
  • 31
  • 189
  • 228
  • 68
    The important point is to be religious about expanding no further than the one root variable. *Everything* must flow from this. – annakata May 19 '09 at 08:54
  • 4
    The syntax of this approach really bothers me. I hate not ending lines with a semicolon and in this solution declaration order matters. I do still think it's a completely valid and in cases a good solution. How do you do callback functions on a JQUery call with this approach? – Hungry Beast May 01 '10 at 18:32
  • 1
    I have a problem making this kind of namespace work with IE7, as posted here: http://stackoverflow.com/questions/4492372/javascript-namespace-and-problem-with-ie7 - not sure whether it has anything to do with the namespace declaration though. It works fine in all "standard" browsers including IE8 – Carles Barrobés Dec 20 '10 at 17:54
  • 24
    This does not create a closure for your code - it makes it tedious to call your other functions because they always have to look like: yourNamespace.bar(); I made an open source project JUST to address this design problem: http://github.com/mckoss/namespace. – mckoss Mar 18 '11 at 22:32
  • 28
    annakata: "The important point is to be religious about expanding no further than the one root variable."- Why is this? – user406905 Mar 30 '11 at 19:22
  • 2
    @user406905: Because then you'd have *two* global identifiers, everything should live under the one namespace. – alex Dec 28 '11 at 23:18
  • 3
    @alex: I can't speak for user406905, but my interpretation of what annakata said is that you should have the one "level" of properties and methods underneath the root namespace. In other words, do me.myselfAndI rather than me.myself.and.i so you have as shallow an object structure as possible. Of course I might have misinterpreted this. – natlee75 Jan 12 '12 at 19:06
  • 12
    @alex - why should there be a shallow object structure? – Ryan May 14 '12 at 19:42
  • 28
    @Ryan I meant that everything should be under `MyApp`, e.g. `MyApp.Views.Profile = {}` rather than `MyApp.users = {}` and `MyViews.Profile = {}`. Not necessarily that there should only be two levels depth. – alex May 14 '12 at 23:29
  • 1
    It's worth wrapping `yourNamespace` in a lexical closure. – James M. Lay Oct 02 '15 at 23:39
  • @user406905 The big reason of namespaces is to minimize the chance of name collisions in the future within the global namespace that all code share. The key is to pollute the global namespace the least possible with local/custom variables, to avoid name collisions in the future, which are hard to troubleshoot and quickly becomes a mess. So the tradeoff is all your local variables will reside in that one namespace. And try to give it a name that hopefully another component will not use one day. That's what this best practice is about. – Wadih M. Apr 07 '21 at 16:06
357

Another way to do it, which I consider it to be a little bit less restrictive than the object literal form, is this:

var ns = new function() {

    var internalFunction = function() {

    };

    this.publicFunction = function() {

    };
};

The above is pretty much like the module pattern and whether you like it or not, it allows you to expose all your functions as public, while avoiding the rigid structure of an object literal.

Ionuț G. Stan
  • 176,118
  • 18
  • 189
  • 202
  • 4
    It's kind of blindsided me that anyone wouldn't love OLN. I just... what's not to love? What's so rigid? – annakata May 19 '09 at 08:50
  • 18
    1. There's a difference between OLN and the module pattern. 2. I don't /always/ like OLN as you have to remember to not put the last trailing comma and all your attributes must be initialized with a value (like null or undefined). Also, if you need closures for member functions, you will need small function factories for each of those methods. Another thing is that you must enclose all your control structures inside functions, whereas the above form does not impose that. That's not to say that I don't use OLN, is just that sometimes I don't like it. – Ionuț G. Stan May 19 '09 at 09:21
  • this style is compatible with my javascript editor (eclipse), as in, it can do auto formatting and indentation. – Titi Wangsa bin Damhore Oct 07 '10 at 03:41
  • 11
    I like this approach because it allows for private functions, variables, and pseudo-constants (i.e. var API_KEY = 12345;). – Lawrence Barsanti Oct 14 '10 at 14:30
  • 12
    I like this better than the comma separated object container that's voted higher. I don't see any shortcomings in comparison, either. Am I missing something? – Lucent Nov 07 '10 at 01:16
  • anybody knows why jQuery is not using this approach but the comma separated ? – Omu Mar 23 '11 at 08:05
  • 4
    This pattern works for singleton objects, but `jQuery` is a constructor function. In my example you can't call `ns()`, and jQuery needs this. – Ionuț G. Stan Mar 23 '11 at 10:20
  • 3
    Now if JSLint would not complain about this legit structure everything will be so much better :) – Adi Roiban Apr 15 '11 at 12:50
  • 7
    JS Newbie here... why is it that I don't have to type `ns().publicFunction()`, that is... `ns.publicFunction()` works. – John Kraft Aug 11 '11 at 21:46
  • 15
    @John Kraft, it's necause of the `new` keyword in front of the `function` keyword. Basically, what is doing is that it's declaring an anonymous function (and as a function, it is as well a constructor), and it then immediately invokes it as a constructor using `new`. As such, the final value that gets stored inside `ns` is an (unique) instance of that anonymous constructor. Hope it makes sense. – Ionuț G. Stan Aug 12 '11 at 07:19
  • 3
    kind of a gotchya with this approach: if you want to access 'public' members or methods within an 'internal' method, you have to add on the 'class' name. Example: ns.publicFunction(); or ns.publicMember; – BumbleB2na Sep 12 '11 at 21:41
  • 4
    Also worth mentioning that in the above examples `this` refers to what you would expect in `publicFunction`, but refers to the global object in `internalFunction`. I usually add `var self = this` at the top to avoid confusion. – Flash Jul 20 '12 at 05:55
160

Is there a more elegant or succinct way of doing this?

Yes. For example:

var your_namespace = your_namespace || {};

then you can have

var your_namespace = your_namespace || {};
your_namespace.Foo = {toAlert:'test'};
your_namespace.Bar = function(arg) 
{
    alert(arg);
};
with(your_namespace)
{
   Bar(Foo.toAlert);
}
Michael Easter
  • 23,733
  • 7
  • 76
  • 107
Alex Pacurar
  • 5,801
  • 4
  • 26
  • 33
  • 1
    this gives me an error in IE7. var your_namespace = (typeof your_namespace == "undefined" || !your_namespace ) ? {} : your_namespace ; works better. – mjallday Nov 05 '10 at 07:28
  • 9
    it should be var your_namespace = your_namespace = your_namespace || {} Works in every browser ;) – Palo Mar 09 '11 at 11:45
  • +1 from me! Thin one works as Jaco Pretorius answer by expanding one library to different files or different places inside the same file. Just brilliant! – centurian Apr 20 '13 at 07:34
  • 2
    @Palo Can you please explain why it should be like this? `var your_namespace = your_namespace = your_namespace || {}` – Sriram May 29 '13 at 12:05
  • What advantage would this have over `var your_namespace = {};`? – Jack Jul 28 '14 at 20:40
  • 6
    you would have the possibility to extend the your_namespace object in different js files. When using var your_namespace = {} you cannot do that, as the object will be overridden by each file – Alex Pacurar Jul 29 '14 at 07:42
  • This is the defacto "standard" way that commercial web development houses do this (from my experience). It's the clearest, most concise, most readable way of achieving the "namespace" paradigm within javascript as far as I'm concerned. – jropella Jan 23 '16 at 00:20
  • 1
    And yet the [MDN discourages](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with) the use of `with`? – aamarks May 22 '18 at 21:00
97

I normally build it in a closure:

var MYNS = MYNS || {};

MYNS.subns = (function() {

    function privateMethod() {
        // Do private stuff, or build internal.
        return "Message";
    }

    return {
        someProperty: 'prop value',
        publicMethod: function() {
            return privateMethod() + " stuff";
        }
    };
})();

My style over the years has had a subtle change since writing this, and I now find myself writing the closure like this:

var MYNS = MYNS || {};

MYNS.subns = (function() {
    var internalState = "Message";

    var privateMethod = function() {
        // Do private stuff, or build internal.
        return internalState;
    };
    var publicMethod = function() {
        return privateMethod() + " stuff";
    };

    return {
        someProperty: 'prop value',
        publicMethod: publicMethod
    };
})();

In this way I find the public API and implementation easier to understand. Think of the return statement as being a public interface to the implementation.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Brett Ryan
  • 26,937
  • 30
  • 128
  • 163
  • 4
    Should you not check for `MYNS.subns = MYNS.subns || {}` ?? – Paranoid Android Aug 12 '14 at 11:58
  • A good point that should be the exercise to the developers intent. You need to consider what to do when it does exist, replace it, error, use existing or version check and conditionally replace. I've had differing situations that call for each variants. In most cases you possibly have this as a low risk edge case and replacing can be beneficial, consider a rogue module that tried to hijack the NS. – Brett Ryan Aug 12 '14 at 15:35
  • 3
    There is an explanation of this approach in the Book "Speaking Javascript" at page 412 if anyone has it, under the heading "Quick and Dirty Modules". – Soferio Jan 30 '15 at 07:51
  • Will have to check it out. Was it talking negative due to the "dirty" in the heading? lol – Brett Ryan Jan 30 '15 at 09:34
  • 3
    Optimization tip: while `var foo = function` and `function foo` are similar, being private; due to JavaScript's dynamically-typed nature, the latter is *slightly* faster as it skips a few instructions in most interpreters' pipelines. With `var foo`, the type system has to get invoked to find out what type is being assigned to said var, while with `function foo`, the type system automatically knows it's a function, so a couple function calls get skipped, which translates to fewer invocations of CPU instructions like `jmp`, `pushq`, `popq`, etc, which translates to a shorter CPU pipeline. – Braden Best Dec 14 '15 at 20:12
  • Also, I would argue that `function foo` is more readable than `var foo = function`, because even though the `var` syntax allows for vertical alignment, the `function` syntax is explicit, and immediately clear to a human reading the code. The `var` syntax leads to slightly longer mental parsing. So in a way, the `function` syntax optimizes for both CPU *and* brain pipelines. Neato! This is just a matter of taste, but the way I would have done that last snippet is like this: http://pastebin.com/Zkk49aj9. It's subtle, but I find it faster to read. – Braden Best Dec 14 '15 at 20:28
  • @B1KMusic that's both incorrect and poor advice. There's a distinct difference between the two. Using an assignment declares the function at runtime which allows delayed AND conditional function declarations, using `function myFunc` is defined at script evaluation and thus can not be declared conditionally. If you can any way prove your claims at efficiency then please provide it, you may find the opposite is true. For something defined only once it's not something you should be trying to optimise anyway. – Brett Ryan Dec 19 '15 at 00:04
  • 2
    @brett oops. You're right. I was thinking of a different scripting language. Though I still insist the `function foo` syntax is more readable. And I still like my version. – Braden Best Dec 19 '15 at 00:41
59

Because you may write different files of JavaScript and later combine or not combine them in an application, each needs to be able to recover or construct the namespace object without damaging the work of other files...

One file might intend to use the namespace namespace.namespace1:

namespace = window.namespace || {};
namespace.namespace1 = namespace.namespace1 || {};

namespace.namespace1.doSomeThing = function(){}

Another file might want to use the namespace namespace.namespace2:

namespace = window.namespace || {};
namespace.namespace2 = namespace.namespace2 || {};

namespace.namespace2.doSomeThing = function(){}

These two files can live together or apart without colliding.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Fentex
  • 599
  • 4
  • 2
  • 1
    I've found this to be a very useful method for organizing client script into multiple files in large applications where functionality needs to be modular. – DVK Aug 15 '16 at 15:18
  • Question asking specifically for multiple files: http://stackoverflow.com/questions/5150124/splitting-a-javascript-namespace-into-multiple-files – Ciro Santilli OurBigBook.com Oct 18 '16 at 12:36
53

Here's how Stoyan Stefanov does it in his JavaScript Patterns book which I found to be very good (it also shows how he does comments that allows for auto-generated API documentation, and how to add a method to a custom object's prototype):

/**
* My JavaScript application
*
* @module myapp
*/

/** @namespace Namespace for MYAPP classes and functions. */
var MYAPP = MYAPP || {};

/**
* A maths utility
* @namespace MYAPP
* @class math_stuff
*/
MYAPP.math_stuff = {

    /**
    * Sums two numbers
    *
    * @method sum
    * @param {Number} a First number
    * @param {Number} b Second number
    * @return {Number} Sum of the inputs
    */
    sum: function (a, b) {
        return a + b;
    },

    /**
    * Multiplies two numbers
    *
    * @method multi
    * @param {Number} a First number
    * @param {Number} b Second number
    * @return {Number} The inputs multiplied
    */
    multi: function (a, b) {
        return a * b;
    }
};

/**
* Constructs Person objects
* @class Person
* @constructor
* @namespace MYAPP
* @param {String} First name
* @param {String} Last name
*/
MYAPP.Person = function (first, last) {

    /**
    * First name of the Person
    * @property first_name
    * @type String
    */
    this.first_name = first;

    /**
    * Last name of the Person
    * @property last_name
    * @type String
    */
    this.last_name = last;
};

/**
* Return Person's full name
*
* @method getName
* @return {String} First name + last name
*/
MYAPP.Person.prototype.getName = function () {
    return this.first_name + ' ' + this.last_name;
};
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ciarán Bruen
  • 5,221
  • 13
  • 59
  • 69
33

I use this approach:

var myNamespace = {}
myNamespace._construct = function()
{
    var staticVariable = "This is available to all functions created here"

    function MyClass()
    {
       // Depending on the class, we may build all the classes here
       this.publicMethod = function()
       {
          //Do stuff
       }
    }

    // Alternatively, we may use a prototype.
    MyClass.prototype.altPublicMethod = function()
    {
        //Do stuff
    }

    function privateStuff()
    {
    }

    function publicStuff()
    {
       // Code that may call other public and private functions
    }

    // List of things to place publically
    this.publicStuff = publicStuff
    this.MyClass = MyClass
}
myNamespace._construct()

// The following may or may not be in another file
myNamespace.subName = {}
myNamespace.subName._construct = function()
{
   // Build namespace
}
myNamespace.subName._construct()

External code can then be:

var myClass = new myNamespace.MyClass();
var myOtherClass = new myNamepace.subName.SomeOtherClass();
myNamespace.subName.publicOtherStuff(someParameter);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
  • Great detail! Thanks! Just wondering what's your take on Namespace.js. I've never used it myself, so I'm wondering if someone with your knowledge/skill/experience would consider using it. – John Oct 19 '10 at 14:43
  • I like it! On the other hand I get exception on first line of this external code, saying: 'myNameSpace.MyClass' [undefined] is not constructor. maybe it depends in JS implementation? :/ – yoosiba Feb 16 '11 at 12:37
  • @yossiba: Possibly. The code above is fairly standard stuff. In standard JS any function can be used as a constructor, there is nothing you need to do to mark a function as specifically for being used as a constructor. Are you using an unusual flavor like ActionScript or something? – AnthonyWJones Feb 16 '11 at 12:55
  • @Anthony its better to use var MYNAMESPACE = MYNAMESPACE || {}; just using var myNamespace = {} is unsafe and moreover its better to declare your namespace in caps – paul Aug 04 '11 at 22:55
  • 10
    @paul: "Better" can be quite subjective. I hate reading code that SHOUTS at me so I avoid using identifiers that use all uppercase. Whilst `ns = ns || {}` might seem more defensive it can lead to other unexpected results. – AnthonyWJones Aug 05 '11 at 12:22
  • @Anthony its just an suggestion and following the conventions. Moreover, its all about your personal preference. – paul Aug 05 '11 at 15:49
  • @AnthonyWJones, apart from mistakenly using an unintended variable, what unexpected results do you anticipate with `ns = ns || {}`? A more defensive approach could be `var n = n && n.name === "NSNAME" ? n : { name: "NSNAME"};` – Brett Ryan Feb 28 '14 at 02:13
32

This is a follow-up to user106826's link to Namespace.js. It seems the project moved to GitHub. It is now smith/namespacedotjs.

I have been using this simple JavaScript helper for my tiny project and so far it seems to be light yet versatile enough to handle namespacing and loading modules/classes. It would be great if it would allow me to import a package into a namespace of my choice, not just the global namespace... sigh, but that's besides the point.

It allows you to declare the namespace then define objects/modules in that namespace:

Namespace('my.awesome.package');
my.awesome.package.WildClass = {};

Another option is to declare the namespace and its contents at once:

Namespace('my.awesome.package', {
    SuperDuperClass: {
        saveTheDay: function() {
            alert('You are welcome.');
        }
    }
});

For more usage examples, look at the example.js file in the source.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rudy Lattae
  • 851
  • 1
  • 11
  • 13
  • 2
    As long as you remember this has some performance implications, as each time you access my.awesome.package.WildClass you're accessing the awesome property of my, the package property of my.awesome, and the WildClass property of my.awesome.package. – SamStephens Sep 19 '11 at 02:25
29

Sample:

var namespace = {};
namespace.module1 = (function(){

    var self = {};
    self.initialized = false;

    self.init = function(){
        setTimeout(self.onTimeout, 1000)
    };

    self.onTimeout = function(){
        alert('onTimeout')
        self.initialized = true;
    };

    self.init(); /* If it needs to auto-initialize, */
    /* You can also call 'namespace.module1.init();' from outside the module. */
    return self;
})()

You can optionally declare a local variable, same, like self and assign local.onTimeout if you want it to be private.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jim Jose
  • 1,319
  • 11
  • 17
16

The Module pattern was originally defined as a way to provide both private and public encapsulation for classes in conventional software engineering.

When working with the Module pattern, we may find it useful to define a simple template that we use for getting started with it. Here's one that covers name-spacing, public and private variables.

In JavaScript, the Module pattern is used to further emulate the concept of classes in such a way that we're able to include both public/private methods and variables inside a single object, thus shielding particular parts from the global scope. What this results in is a reduction in the likelihood of our function names conflicting with other functions defined in additional scripts on the page.

var myNamespace = (function () {

  var myPrivateVar, myPrivateMethod;

  // A private counter variable
  myPrivateVar = 0;

  // A private function which logs any arguments
  myPrivateMethod = function( foo ) {
      console.log( foo );
  };

  return {

    // A public variable
    myPublicVar: "foo",

    // A public function utilizing privates
    myPublicFunction: function( bar ) {

      // Increment our private counter
      myPrivateVar++;

      // Call our private method using bar
      myPrivateMethod( bar );

    }
  };

})();

Advantages

why is the Module pattern a good choice? For starters, it's a lot cleaner for developers coming from an object-oriented background than the idea of true encapsulation, at least from a JavaScript perspective.

Secondly, it supports private data - so, in the Module pattern, public parts of our code are able to touch the private parts, however the outside world is unable to touch the class's private parts.

Disadvantages

The disadvantages of the Module pattern are that as we access both public and private members differently, when we wish to change visibility, we actually have to make changes to each place the member was used.

We also can't access private members in methods that are added to the object at a later point. That said, in many cases the Module pattern is still quite useful and when used correctly, certainly has the potential to improve the structure of our application.

The Revealing Module Pattern

Now that we're a little more familiar with the module pattern, let’s take a look at a slightly improved version - Christian Heilmann’s Revealing Module pattern.

The Revealing Module pattern came about as Heilmann was frustrated with the fact that he had to repeat the name of the main object when we wanted to call one public method from another or access public variables.He also disliked the Module pattern’s requirement for having to switch to object literal notation for the things he wished to make public.

The result of his efforts was an updated pattern where we would simply define all of our functions and variables in the private scope and return an anonymous object with pointers to the private functionality we wished to reveal as public.

An example of how to use the Revealing Module pattern can be found below

var myRevealingModule = (function () {

        var privateVar = "Ben Cherry",
            publicVar = "Hey there!";

        function privateFunction() {
            console.log( "Name:" + privateVar );
        }

        function publicSetName( strName ) {
            privateVar = strName;
        }

        function publicGetName() {
            privateFunction();
        }


        // Reveal public pointers to
        // private functions and properties

        return {
            setName: publicSetName,
            greeting: publicVar,
            getName: publicGetName
        };

    })();

myRevealingModule.setName( "Paul Kinlan" );

Advantages

This pattern allows the syntax of our scripts to be more consistent. It also makes it more clear at the end of the module which of our functions and variables may be accessed publicly which eases readability.

Disadvantages

A disadvantage of this pattern is that if a private function refers to a public function, that public function can't be overridden if a patch is necessary. This is because the private function will continue to refer to the private implementation and the pattern doesn't apply to public members, only to functions.

Public object members which refer to private variables are also subject to the no-patch rule notes above.

Divyanshu Rawat
  • 4,421
  • 2
  • 37
  • 53
16

If you need the private scope:

var yourNamespace = (function() {

  //Private property
  var publicScope = {};

  //Private property
  var privateProperty = "aaa"; 

  //Public property
  publicScope.publicProperty = "bbb";

  //Public method
  publicScope.publicMethod = function() {
    this.privateMethod();
  };

  //Private method
  function privateMethod() {
    console.log(this.privateProperty);
  }

  //Return only the public parts
  return publicScope;
}());

yourNamespace.publicMethod();

else if you won't ever use the private scope:

var yourNamespace = {};

yourNamespace.publicMethod = function() {
    // Do something...
};

yourNamespace.publicMethod2 = function() {
    // Do something...
};

yourNamespace.publicMethod();
tedi
  • 6,350
  • 5
  • 52
  • 67
15

You can declare a simple function to provide namespaces.

function namespace(namespace) {
    var object = this, tokens = namespace.split("."), token;

    while (tokens.length > 0) {
        token = tokens.shift();

        if (typeof object[token] === "undefined") {
            object[token] = {};
        }

        object = object[token];
    }

    return object;
}

// Usage example
namespace("foo.bar").baz = "I'm a value!";
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dnemoga
  • 214
  • 3
  • 5
10

I'm 7 years late to the party, but did quite a bit of work around this 8 years ago:

It is important to be able to easily and efficiently create multiple nested namespaces to keep a complex web application organized and manageable, while respecting the JavaScript global namespace (preventing namespace pollution), and with not clobbering any existing objects in the namespace path while doing so.

From the above, this was my circa-2008 solution:

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

This isn't creating a namespace, but provides a function for creating namespaces.

This can be condensed to a minified one-liner:

var namespace=function(c,f,b){var e=c.split(f||"."),g=b||window,d,a;for(d=0,a=e.length;d<a;d++){g=g[e[d]]=g[e[d]]||{}}return g};

Example of use:

namespace("com.example.namespace");
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:

com.example.namespace.test();

If you don't need support for legacy browsers, an updated version:

const namespace = function(name, separator, container){
    var o = container || window;
    name.split(separator || '.').forEach(function(x){
        o = o[x] = o[x] || {};
    });
    return o;
};

Now, I'd be leery of exposing namespace to the global namespace itself. (Too bad the base language doesn't provide this for us!) So I'd typically use this myself in a closure, such as:

(function(){
 const namespace = function(name, separator, container){
  var o = container || window;
  name.split(separator || '.').forEach(function(x){
   o = o[x] = o[x] || {};
  });
  return o;
 };
 const ns = namespace("com.ziesemer.myApp");
 
 // Optional:
 ns.namespace = ns;
 
 // Further extend, work with ns from here...
}());

console.log("\"com\":", com);

In a larger application, this only needs to be defined once at the beginning of a page load (for client-based web apps). Additional files can then reuse the namespace function if kept (included as "optional" in the above). At worst, if this function is re-declared a few times - it's only a few lines of code, and less if minified.

ziesemer
  • 27,712
  • 8
  • 86
  • 94
  • This is great, but I have a question about `let` and `const`. Once you have created a namespace `namespace("com.ziesemer.myApp")`, is it possible to designate a property/object as `const` or `let`? Like `com.ziesemer.myApp.logger` - it seems to me that this can never be declared as `const`. I think with this I can't adopt some of those newer language features. Note: adopting the new Javascript modules is not an option unfortunately. – onefootswill May 22 '22 at 22:42
  • @onefootswill - What you're looking for is not applicable here, as you're not strictly declaring variables - but new properties on to existing objects. – ziesemer May 23 '22 at 02:23
  • yep. I realise that. The question was put to me by our architect, who is fighting me on the inclusion of this approach. He seems content with polluting the global namespace in the creaky, old, low quality code-base. Some people ¯\_(ツ)_/¯ – onefootswill May 23 '22 at 21:29
9

I created namespace which is inspired by Erlang's modules. It is a very functional approach, but that is how I write my JavaScript code these days.

It gives a closure a global namespace and exposes a defined set functions within that closure.

(function(){

  namespace("images", previous, next);
  // ^^ This creates or finds a root object, images, and binds the two functions to it.
  // It works even though those functions are not yet defined.

  function previous(){ ... }

  function next(){ ... }

  function find(){ ... } // A private function

})();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
The Who
  • 6,552
  • 5
  • 36
  • 33
8

After porting several of my libraries to different projects, and having to constantly be changing the top level (statically named) namespace, I've switched to using this small (open source) helper function for defining namespaces.

global_namespace.Define('startpad.base', function(ns) {
    var Other = ns.Import('startpad.other');
    ....
});

Description of the benefits are at my blog post. You can grab the source code here.

One of the benefits I really like is isolation between modules with respect to load order. You can refer to an external module BEFORE it is loaded. And the object reference you get will be filled in when the code is available.

mckoss
  • 6,764
  • 6
  • 33
  • 31
8

I use the following syntax for the namespace.

var MYNamespace = MYNamespace|| {};

 MYNamespace.MyFirstClass = function (val) {
        this.value = val;
        this.getValue = function(){
                          return this.value;
                       };
    }

var myFirstInstance = new MYNamespace.MyFirstClass(46);
alert(myFirstInstance.getValue());

jsfiddle: http://jsfiddle.net/rpaul/4dngxwb3/1/

Razan Paul
  • 13,618
  • 3
  • 69
  • 61
6

I think you all use too much code for such a simple problem. No need to make a repo for that. Here's a single line function.

namespace => namespace.split(".").reduce((last, next) => (last[next] = (last[next] || {})), window);

Try it :

// --- definition ---
const namespace = name => name.split(".").reduce((last, next) => (last[next] = (last[next] || {})), window);

// --- Use ----
const c = namespace("a.b.c");
c.MyClass = class MyClass {};

// --- see ----
console.log("a : ", a);
Yairopro
  • 9,084
  • 6
  • 44
  • 51
5

ES6 Modules Namespace imports

// circle.js
export { name, draw, reportArea, reportPerimeter };
// main.js
import * as Circle from './modules/circle.js';

// draw a circle
let circle1 = Circle.draw(myCanvas.ctx, 75, 200, 100, 'green');
Circle.reportArea(circle1.radius, reportList);
Circle.reportPerimeter(circle1.radius, reportList);

This grabs all the exports available inside circle.js, and makes them available as members of an object Circle, effectively giving it its own namespace.

Pavel Chuchuva
  • 22,633
  • 10
  • 99
  • 115
3

My favorite pattern has become lately this:

var namespace = (function() {
  
  // expose to public
  return {
    a: internalA,
    c: internalC
  }

  // all private
  
  /**
   * Full JSDoc
   */
  function internalA() {
    // ...
  }
  
  /**
   * Full JSDoc
   */
  function internalB() {
    // ...
  }
  
  /**
   * Full JSDoc
   */
  function internalC() {
    // ...
  }
  
  /**
   * Full JSDoc
   */
  function internalD() {
    // ...
  }
  
})();

Of course, return can be at the end, but if only function declarations follow it, it's much easier to see what's the namespace all about, and what API is exposed.

The pattern of using function expressions in such cases results in not being able to know what methods are exposed without going over the entire code.

nomæd
  • 421
  • 5
  • 13
  • Hi, how do you call public functions from your snippet? I've tried `namespace.a();` – olimart Aug 24 '16 at 19:07
  • @olivier yes, that's the idea. Although now with ES6, I usually use the shorthand syntax of object literals (https://ponyfoo.com/articles/es6-object-literal-features-in-depth) – nomæd Sep 20 '16 at 19:01
  • I just want to make emphasis on the set of `()` at the end of the function definition. They are required and it's easy to miss them. I had the same issue as @olimart and solved it by adding them. – Andres Jun 09 '21 at 18:25
2

I like Jaco Pretorius' solution, but I wanted to make the "this" keyword a bit more useful by pointing it to the module/namespace object. My version of skillet:

(function ($, undefined) {

    console.log(this);

}).call(window.myNamespace = window.myNamespace || {}, jQuery);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
haxpanel
  • 4,402
  • 4
  • 43
  • 71
2

JavaScript does not yet have a native representation of namespaces, but TypeScript does.

For example, you could use the following TS code (playground)

namespace Stack {
    export const hello = () => console.log('hi')
}

Stack.hello()

If you can't update your code to TS, you can at least use the pattern employed by TS when generating the JS output for namespaces, which looks like this:

var Stack;
(function (Stack) {
    Stack.hello = () => console.log('hi');
})(Stack || (Stack = {}));
Stack.hello();

Further Reading:

KyleMit
  • 30,350
  • 66
  • 462
  • 664
1

Quite a follow-up of Ionuț G. Stan's answer, but showing the benefits of uncluttered code by using var ClassFirst = this.ClassFirst = function() {...}, which takes advantage of JavaScript's closure scoping for less namespace cluttering for classes in the same namespace.

var Namespace = new function() {
    var ClassFirst = this.ClassFirst = function() {
        this.abc = 123;
    }

    var ClassSecond = this.ClassSecond = function() {
        console.log("Cluttered way to access another class in namespace: ", new Namespace.ClassFirst().abc);
        console.log("Nicer way to access a class in same namespace: ", new ClassFirst().abc);
    }
}

var Namespace2 = new function() {
    var ClassFirst = this.ClassFirst = function() {
        this.abc = 666;
    }

    var ClassSecond = this.ClassSecond = function() {
        console.log("Cluttered way to access another class in namespace: ", new Namespace2.ClassFirst().abc);
        console.log("Nicer way to access a class in same namespace: ", new ClassFirst().abc);
    }
}

new Namespace.ClassSecond()
new Namespace2.ClassSecond()

Output:

Cluttered way to access another class in namespace: 123
Nicer way to access a class in same namespace: 123
Cluttered way to access another class in namespace: 666
Nicer way to access a class in same namespace: 666
kungfooman
  • 4,473
  • 1
  • 44
  • 33
1

We can use it independently in this way:

var A = A|| {};
A.B = {};

A.B = {
    itemOne: null,
    itemTwo: null,
};

A.B.itemOne = function () {
    //..
}

A.B.itemTwo = function () {
    //..
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ganesh
  • 307
  • 5
  • 13
1

In JavaScript there are no predefined methods to use namespaces. In JavaScript we have to create our own methods to define NameSpaces. Here is a procedure we follow in Oodles technologies.

Register a NameSpace Following is the function to register a name space

//Register NameSpaces Function
function registerNS(args){
 var nameSpaceParts = args.split(".");
 var root = window;

 for(var i=0; i < nameSpaceParts.length; i++)
 {
  if(typeof root[nameSpaceParts[i]] == "undefined")
   root[nameSpaceParts[i]] = new Object();

  root = root[nameSpaceParts[i]];
 }
}

To register a Namespace just call the above function with the argument as name space separated by '.' (dot). For Example Let your application name is oodles. You can make a namespace by following method

registerNS("oodles.HomeUtilities");
registerNS("oodles.GlobalUtilities");
var $OHU = oodles.HomeUtilities;
var $OGU = oodles.GlobalUtilities;

Basically it will create your NameSpaces structure like below in backend:

var oodles = {
    "HomeUtilities": {},
    "GlobalUtilities": {}
};

In the above function you have register a namespace called "oodles.HomeUtilities" and "oodles.GlobalUtilities". To call these namespaces we make an variable i.e. var $OHU and var $OGU.

These variables are nothing but an alias to Intializing the namespace. Now, Whenever you declare a function that belong to HomeUtilities you will declare it like following:

$OHU.initialization = function(){
    //Your Code Here
};

Above is the function name initialization and it is put into an namespace $OHU. and to call this function anywhere in the script files. Just use following code.

$OHU.initialization();

Similarly, with the another NameSpaces.

Hope it helps.

sg7
  • 6,108
  • 2
  • 32
  • 40
1

I've written another namespacing library that works a bit more like packages / units do in other languages. It allows you to create a package of JavaScript code and the reference that package from other code:

File hello.js

Package("hello", [], function() {
  function greeting() {
    alert("Hello World!");
  }
  // Expose function greeting to other packages
  Export("greeting", greeting);
});

File Example.js

Package("example", ["hello"], function(greeting) {
  // Greeting is available here
  greeting();  // Alerts: "Hello World!"
});

Only the second file needs to be included in the page. Its dependencies (file hello.js in this example) will automatically be loaded and the objects exported from those dependencies will be used to populate the arguments of the callback function.

You can find the related project in Packages JS.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Stijn de Witt
  • 40,192
  • 13
  • 79
  • 80
  • 1
    @peter-mortensen Were these edits to my answer from '11 really necessary? It's definitely not vandalism what you are doing, don't get me wrong, but they are very superficial. I would prefer to remain the sole author of posts like these unless you really add something good. – Stijn de Witt Dec 28 '15 at 21:23
1

If using a Makefile you can do this.

// prelude.hjs
billy = new (
    function moduleWrapper () {
    const exports = this;

// postlude.hjs
return exports;
})();

// someinternalfile.js
function bob () { console.log('hi'); }
exports.bob = bob;

// clientfile.js
billy.bob();

I prefer to use a Makefile anyway once I get to about 1000 lines because I can effectively comment out large swaths of code by removing a single line in the makefile. It makes it easy to fiddle with stuff. Also, with this technique the namespace only appears once in the prelude so it's easy to change and you don't have to keep repeating it inside the library code.

A shell script for live development in the browser when using a makefile:

while (true); do make; sleep 1; done

Add this as a make task 'go' and you can 'make go' to keep your build updated as you code.

Samuel Danielson
  • 5,231
  • 3
  • 35
  • 37
0

My habit is to use function myName() as property storage, and then var myName as "method" holder...

Whether this is legitimate enough or not, beat me! I am relying on my PHP logic all the time, and things simply work. :D

function myObj() {
    this.prop1 = 1;
    this.prop2 = 2;
    this.prop3 = 'string';
}

var myObj = (
 (myObj instanceof Function !== false)
 ? Object.create({

     $props: new myObj(),
     fName1: function() { /* code..  */ },
     fName2: function() { /* code ...*/ }
 })
 : console.log('Object creation failed!')
);

if (this !== that) myObj.fName1(); else myObj.fName2();

You can also do it in a 'vice versa' way to check before object creation which is much better:

function myObj() {
    this.prop1 = 1;
    this.prop2 = 2;
    this.prop3 = 'string';
}

var myObj = (
    (typeof(myObj) !== "function" || myObj instanceof Function === false)
    ? new Boolean()
    : Object.create({
        $props: new myObj(),
        init: function () { return; },
        fName1: function() { /* code..  */ },
        fName2: function() { /* code ...*/ }
    })
);

if (myObj instanceof Boolean) {
    Object.freeze(myObj);
    console.log('myObj failed!');
    debugger;
}
else
    myObj.init();

Reference to this: JavaScript: Creating Object with Object.create()

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Spooky
  • 1,235
  • 15
  • 17
0

JavaScript doesn’t support namespace by default. So if you create any element(function, method, object, variable) then it becomes global and pollute the global namespace. Let's take an example of defining two functions without any namespace,

function func1() {
    console.log("This is a first definition");

}
function func1() {
    console.log("This is a second definition");
}
func1(); // This is a second definition

It always calls the second function definition. In this case, namespace will solve the name collision problem.

vishu2124
  • 4,243
  • 2
  • 14
  • 10