JavaScript namespace __java

Source: Internet
Author: User

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"); 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.