A. What is a namespace
The namespace (English: Namespace) represents the visible range of identifiers (identifier). An identifier can be defined in more than one namespace, and its meaning in different namespaces is irrelevant. In this way, you can define any identifiers in a new namespace that will not conflict with any existing identifiers because existing definitions are in other namespaces.
Two. Role of the name space
When a project is large, both its own code, and the reference to the external library, when their own library and external library of the names of objects, no namespace will not be able to distinguish them.
Three. Universal namespace functions
There is no built-in namespace in the syntax of the JavaScript language, but this feature is very easy to implement. A property added to a namespace may already exist, so before adding a property or creating a namespace, we should check that the namespace exists.
var fn = fn | | {};
If FN.FN1.FN2 is defined, then:
var fn = fn | | {};
var fn.fn1 = Fn.fn1 | | {};
var FN.fn1.fn2 = FN.fn1.fn2 | | {};
You can see that each create a namespace or add a property, you need to do an additional check on the object or attribute, resulting in a large number of duplicate code, which violates the dry principle, but also the reason for generating namespace functions. We hope to produce the above effect through the following namespace function calls:
var fn = fn | |
{};
Fn.namespace = function (ns_string) {var parts = ns_string.split ("."), parent = FN, I;
if (parts[0] = = "FN") {left = Parts.slice (1); for (i = 0; i < left.length i = 1) {if (typeof parent[left[i]] = = "Undefi
Ned ") {Parent[left[i]] = {};
Parent = Parent[left[i]]; } x = Fn.namespace ("FN.fn1.fn2");