1

What does it mean, to write JavaScript in your own name scope, apparently it avoids conflicts and conforms to W3C standards but I have no idea what it means or how it is done?

Ben_hawk
  • 2,476
  • 7
  • 34
  • 59

3 Answers3

5

It's a way to minimize the use of global variables (thus avoiding possible conflicts).

var myNS = {}; // Your namespace (an object) = a global var.
myNS.title = "Demo"; // Your variables come here as object properties.
myNS.date = "2012-05-21";

The object properties can be of any type: scalar types, arrays, objects, functions...

5

What I think you mean is namespacing. It means that you should contain your code in a namespace so that you won't pollute the global scope (well, you did pollute it with only one variable and that's about it). Every function and other stuff you intend to create will live in that namespace.

A simple namespace example, in object literal

var ns = {
    foo : function(){...},
    bar : function(){...}
}

You only declared one global, ns. The rest are stored in it and accessible via ns

ns.foo();
ns.bar();

Real life examples can be seen in JS frameworks. For example, we have jQuery and Underscore

//jQuery uses "jQuery" and "$" as namespaces and has "each()"
$.each();

//Underscore has "_" as a namespace and also has "each()"
_.each();

Although they have the same function names, but they live in separate namespaces. This avoids conflict, and helps you identify what belongs where.

Joseph
  • 117,725
  • 30
  • 181
  • 234
3

I guess it means writing functions in your own object, instead of writing global functions:

var myScope = (function() {

    function privateFunction1() {...}
    function privateFunction2() {...}
    function a() {...}
    function b() {...}
    function c() {...}

    return {a: a, b: b, c: c};

})();
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255