Brief Introduction to javaScriptNameSpace _ basic knowledge

Source: Internet
Author: User
Namespace. The main purpose is to avoid conflicts. The following describes how to create your own JavaScript namespace. Creating a JavaScript namespace is actually very simple. You only need to put your own functions, objects, variables, and so on in a pseudo namespace, Which is packaged with an anonymous function.

The Code is as follows:


(Function (){
Function $ (id ){
Return document. getElementById (id );
}
Function alertNodeName (id ){
Alert ($ (id). nodeName );
}
})();


Using this pseudo-namespace can encapsulate and protect all functions, objects, and variables of the user, and because they are in a function, they can also access each other. However, scripts outside the pseudo namespace cannot use these functions.
To enable these functions to be called by scripts outside the pseudo namespace, we first create a window object.

The Code is as follows:


(Function (){
If (! Window. myNamespace) {window ['mynamespace'] = {};}
Function $ (id ){
Return document. getElementById (id );
}
Function alertNodeName (id ){
Alert ($ (id). nodeName );
}
})();


Rename the function to be converted (or do not rename it) and assign it to the window Object window ['mynamespace'].

The Code is as follows:


(Function (){
If (! Window. myNamespace) {window ['mynamespace'] = {};}
Function $ (id ){
Return document. getElementById (id );
}
Function alertNodeName (id ){
Alert ($ (id). nodeName );
}
Window ['mynamespace'] ['shownodename'] = alertNodeName;
})();


In this way, we create our own namespace.

The Code is as follows:





New Document




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.