JavaScript namespace Usage Introduction _javascript Tips

Source: Internet
Author: User
Tags function definition

Students who have used Java and C # are very familiar with namespaces, in the complex system there will be more than n functions, objects, language provided, architecture predefined, so many functions and objects, because the programming specification requires a real meaning of the name, it is inevitable that the duplicate names of the wrong call, and there is no namespace trouble, Not only can classify the organization function and the object, but also can form the isolation, solves the duplicate name question.

Use JavaScript is not so comfortable, JavaScript only function scope, what block Ah, God horse file Ah all think is a namespace, sometimes because of some duplicate problems caused by the wrong people inexplicable, difficult to debug and solve.

A simple example

Copy Code code as follows:

<input type= "button" value= "Test" onclick= "alert ();" />

<script type= "Text/javascript" >
Function alert () {
//.......

Test2 ();
//.......
}

function Test2 () {
Alert (' Test2 ')
}

In an example in different browsers have different performance, IE will report stack over the flow, Firefox will die ... Anyway, it will be an error, a very simple mistake, the code has a custom alert function, in the alert function called the Test2 function, the Test2 function in the intention to call the window alert method, so that the loop call, maybe read you would say so obvious mistake who would commit, But if the custom method is called close (this is often the case), then an internal call to the function of an external file called the Close method of window, so that the error is not hidden a lot.

A simple namespace

Because JavaScript has no file scope, different functions are dispersed in different files, even written by different people, and the probability of duplicate names is greatly increased. Is it enough to be careful? Also not all, there are some unexpected circumstances, such as often used to inheritance, so wrote a not appear in the function name extend, behold in the EcmaScript5 added the Extend function, the necessity of the namespace is reflected.

JavaScript has functions that can be used to write custom functions into a function body, so that variables, objects, and functions within a function are isolated as if they were in a namespace.

Copy Code code as follows:

<input type= "button" value= "Test" onclick= "(New Namespace ()). alert ();" />

<script type= "Text/javascript" >
function namespace () {
This.alert=function () {
Console.log (' Test ');
}
}
</script>

This custom alert method does not conflict with window alert.

Simple evolution

This can be, but there are problems, the biggest problem is the way the call is complex and ugly! Instantiate the object each time it is invoked, and then call its methods, and simply modify the code to automate the instantiation.

Copy Code code as follows:

<input type= "button" value= "Test" onclick= "Ns.alert ();" />

<script type= "Text/javascript" >
(function namespace () {
This.alert=function () {
Console.log (' Test ');
}

Window. Ns=this;
})();
</script>

To understand the above code first of all to understand the "executive function immediately" (This is what the river is called) the skill structure is similar to this

Copy Code code as follows:

(function xxx () {

function body

})();


So write the XXX function can be defined after the automatic execution, looks magical, in fact, the above writing can be broken into such

Copy Code code as follows:

function xxx () {

function body

}

xxx ();

is to define a function and then invoke it using parentheses syntax, and the parentheses outside the function definition only function as a function declaration into a functional definition expression, because only an expression can be invoked using parentheses. After seeing these demon moths, the code is simple, and the custom namespace function finally assigns this to the NS property of window, which is used directly when invoking the ns.xx. It looks a lot better.

Beautify yourself.

The above wording looks good, but the function name namespace seems to be superfluous, can beautify

Copy Code code as follows:

(function () {
This.alert=function () {
Console.log (' Test ');
}

Window. Ns=this;
})();

Become an immediately executed anonymous function, beautify some, but it seems strange, yes, is clearly an instantiated function, why the method definition does not write to prototype, anonymous function how to write prototype ... , you have to use your brain.

Copy Code code as follows:

(function () {
var _ns=function () {

}
_ns.prototype.alert=function () {
Console.log (' Test ');
}
Window. Ns=new _ns ();
})();

Write a few useful functions

Queryselector and Queryselectorall are the new query interfaces provided by the consortium, but the name is long, write a simple, innerHTML attribute is also used, write a simple version of the HTML method of jquery

Copy Code code as follows:

(function () {
var _ns = function () {

}

_ns.prototype.select = function (selector,context) {
var context = Context | | Document
return Context.queryselectorall (selector);
}

_ns.prototype.isarraylike=function (obj) {
if (obj instanceof Array) {
return true;
}

var length=obj.length;
if (Obj.nodetype = = 1 && length) {
return true;
}
return false;
}

_ns.prototype.html = function (obj,value) {
var isarray=this.isarraylike (obj), i=0;

if (typeof value = = ' String ') {
if (!isarray) {
obj.innerhtml = value;
} else {
var length = Obj.length;
while (I < length) {
obj[i].innerhtml = value;
i + 1;
}
}
} else {
if (!isarray) {
return obj.innerhtml;
} else {
return obj[0].innerhtml;
}
}
}

Window. NS = new _ns ();
})();

Such a simple JavaScript library with namespaces is written, do not worry about naming conflicts, but it is inconvenient to use it, do the front end of the students have used jquery, people use it to call a simple, jquery is how to do? To know the funeral, and listen to let's.

Related Article

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.