What is meant by 'JavaScript Namespacing'? [duplicate]
Asked Answered
D

3

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.

Daffie answered 15/12, 2011 at 16:20 Comment(2)
possible duplicate : https://mcmap.net/q/536351/-javascript-namespacing OR https://mcmap.net/q/536352/-how-to-run-a-javascript-function-that-is-inside-a-namespaceLatreshia
Take a look at this question: #5231588Belong
S
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.

Snowonthemountain answered 15/12, 2011 at 16:24 Comment(0)
F
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();
Fatuity answered 15/12, 2011 at 16:32 Comment(0)
S
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

Surcingle answered 15/12, 2011 at 16:23 Comment(1)
Link is dead. Maybe use this one from archive.org?Shostakovich

© 2022 - 2024 — McMap. All rights reserved.