26

Possible Duplicate:
Javascript Namespacing

Im pretty new to JavaScript and was wondering if anyone could give me a good description of what is meant by JavaScript Namespacing?

Also any resources e.g. articles etc, are much appreciated on the subject.

Community
  • 1
  • 1
bc17
  • 323
  • 1
  • 3
  • 6
  • possible duplicate : http://stackoverflow.com/questions/7684452/javascript-namespacing OR http://stackoverflow.com/questions/7712231/javascript-and-namespacing – David Laberge Dec 15 '11 at 16:23
  • Take a look at this question: http://stackoverflow.com/questions/5231088/javascript-namespace-is-this-a-good-pattern – hasser Dec 15 '11 at 16:24

3 Answers3

40

JavaScript is designed in such a way that it is very easy to create global variables that have the potential to interact in negative ways. The practice of namespacing is usually to create an object literal encapsulating your own functions and variables, so as not to collide with those created by other libraries:

var MyApplication = {
  var1: someval,
  var2: someval,
  myFunc: function() {
    // do stuff
  }
};

Then instead of calling myFunc() globally, it would always be called as:

MyApplication.myFunc();

Likewise, var1 always accessed as:

console.log(MyApplication.var1);

In this example, all of our application's code has been namespaced inside MyApplication. It is therefore far less likely that our variables will collide with those created by other libraries or created by the DOM.

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
6

I use this namespacing technique, along with "use strict" outlined by Crockford

var MyNamespace = (function () {
    "use strict"; 

    function SomeOtherFunction() {

    }

    function Page_Load() {

    }

    return { //Expose 
        Page_Load: Page_Load,
        SomeOtherFunction: SomeOtherFunction
    };
} ());

MyNamespace.Page_Load();
bradhanks
  • 422
  • 4
  • 9
CaffGeek
  • 21,856
  • 17
  • 100
  • 184
3

Read up on a simple tutorial Here

Namespacing is used to avoid polluting the global namespace (no window. variables). In truth, each namespace is just a big variable, that has many properties and methods.

This happens, because in javascript you can have whole functions (methods) as variables

Mihalis Bagos
  • 2,500
  • 1
  • 22
  • 32
  • 1
    Link is dead. Maybe use [this one](https://web.archive.org/web/20141209002145/http://blog.stannard.net.au/2011/01/14/creating-namespaces-in-javascript/) from archive.org? – marsnebulasoup Apr 02 '21 at 21:08