Javascript namespace declaration

How can a namespace be declared? I just read “Developing Large Web Applications,” and the author suggests using:

if (!window.YourNamespace) {
  YourNamespace = {};
}

seems pretty simple .. but I see all javascript libraries for declaring namespaces and alternative methods. Isn't there a standard way to do this? Any problems with the above?

+3
source share
7 answers
  var Utils = {
        namespace : function(name) {
                return window[name] = window[name] || {};
        }
  };

or if you prefer to use your method:

if (typeof window.YourNamespace === 'undefined') {
    YourNamespace = {};
}
0
source

I saw that this agreement used several places.

window.YourNamespace = window.YourNamespace || {};
+2
source

, , . , , :

if (!window.Foo) {
  Foo = {};
}
if (!window.Foo.Bar) {
  Foo.Bar = {};
}
if (!window.Foo.Bar.Baz) {
  Foo.Bar.Baz = {};
}
etc...

, :

function namespace(ns) {
  var parts = ns.split(/\./);
  var obj = window;
  for (var i=0; i<parts.length; i++) {
    var p = parts[i];
    if (!obj[p]) {
      obj[p] = {};
    }
    obj = obj[p];
  }
}

:

namespace("Foo.Bar.Baz");

ExtJS , Ext.ns(). .

+2

, , , , , X.Y.Z, , .

0

bob.js :

bob.ns.setNs('YourNamespace', {

    /*define your members here. e.g.:*/
    method1: function () { /*...*/ }
});


// now, merge another, sub-namespace.
bob.ns.setNs('YourNamespace.YourSubNamespace', {

    method2 function () { /*...*/ }
});

//call methods:
YourNamespace.method1();
YourNamespace.YourSubNamespace.method2();
0

javascript , :

var namespace = function(str, root) {
    var chunks = str.split('.');
    if(!root)
        root = window;
    var current = root;
    for(var i = 0; i < chunks.length; i++) {
        if (!current.hasOwnProperty(chunks[i]))
            current[chunks[i]] = {};
        current = current[chunks[i]];
    }
    return current;
};

// ----- USAGE ------

namespace('ivar.util.array');

ivar.util.array.foo = 'bar';
alert(ivar.util.array.foo);

namespace('string', ivar.util);

ivar.util.string.foo = 'baz';
alert(ivar.util.string.foo); 

Try: http://jsfiddle.net/stamat/Kb5xY/ Blog post: http://stamat.wordpress.com/2013/04/12/javascript-elegant-namespace-declaration/

0
source

An example of using a namespace function:

namespace = function(ns){
    arr = ns.split(".")
    parent = window

    var temp

    while( ( temp = arr.shift()) !== undefined){
        parent[temp] = parent[temp] || {}
        parent = parent[temp]
    }
}

Then you can use it like:

namespace("your.own.namespace")

your.own.namespace.Car= function () {

    this.speed = 30; 

}
-1
source

Source: https://habr.com/ru/post/1766195/


All Articles