2.1.5 • Published 8 years ago
simple-js-namespace v2.1.5
simple-js-namespace
Small function to define JavaScript namespaces
##Install
npm install --save simple-js-namespace
##Enable
require("simple-js-namespace");
##Usage example
require("simple-js-namespace");
_namespace = "SOME.NESTED.NAMESPACE";
console.log(SOME);
console.log(SOME.NESTED);
console.log(SOME.NESTED.NAMESPACE);
SOME.NESTED.NAMESPACE.Test = function() {
};
_namespace.Test1 = function() {
};
console.log(SOME.NESTED.NAMESPACE);
_namespace = ".NESTME";
SOME.NESTED.NAMESPACE.NESTME.Test = function() {}
_namespace.Test1 = function() {}
console.log(SOME.NESTED.NAMESPACE);
##Usage description
Define and use a namespace (namespaces are dot-delimited by default)
_namespace = "SOME.NEW.NAMESPACE"
SOME.NEW.NAMESPACE.MyClass = function {
};
//ES 2015
SOME.NEW.NAMESPACE.MyClass2 = class {
};
//Shorthand
_namespace.MyClass3 = ... //function / class / anything
//Assign current namespace to global (reset)
_namespace = global;
//Assign current namespace to already existing one
_namespace = SOME.NEW.NAMESPACE;
Under the hood, namespace is a nested object, i.e.
_namespace = "SOME.NEW.NAMESPACE"
///equals to:
if(! global.SOME) global.SOME = {};
if(! global.SOME.NEW) global.SOME.NEW = {};
if(! global.SOME.NEW.NAMESPACE) global.SOME.NEW.NAMESPACE = {};
Dot notation
There is another way to nest namespaces, which, hovever, must be used with caution, as javascript preserves namespace between files.
_namespace = "SOME.NEW"
SOME.NEW.TestClass = function() {
...
};
_namespace = ".NAMESPACE" //Starts with dot - will add namespace to the last defined
SOME.NEW.NAMESPACE.TestClass = function() {
};
_namespace as shorthand
Property accessor _namespace points to the last defined namespace. It can be used to shorten definitions.
_namespace = "SOME.NEW"
_namespace.TestClass = function() {
...
}; // same as SOME.NEW.TestClass = function ...
_namespace = ".NAMESPACE" //Starts with dot - will add namespace to the last defined
_namespace.TestClass = function() {
...
}; // same as SOME.NEW.NAMESPACE.TestClass = function
_namespace_root_context variable
A global property to hold default context to create namespaces in. Use with caution.
let nsContainer = {};
_namespace_root_context = nsContainer;
_namespace = "SOME.NEW.NAMESPACE"
///now equals to:
if(! nsContainer.SOME) nsContainer.SOME = {};
if(! nsContainer.SOME.NEW) nsContainer.SOME.NEW = {};
if(! nsContainer.SOME.NEW.NAMESPACE) nsContainer.SOME.NEW.NAMESPACE = {};
//ETC
//Export it in NodeJS for example
module.exports = nsContainer;
///Do not forget to reset namespace root at the end of module or js file if you changed it, as it is a global property and its unexpected change may break other modules!
//For browser
_namespace_root_context = window;
//OR for NodeJS
_namespace_root_context = global;