JavaScript Namespaces and Applications (front-end basic series)

Source: Internet
Author: User
Tags sessionstorage

The so-called code, when you casually name a variable: var name = "Ukerxi"; is a code, but when your code is written, for the subsequent maintenance and reading of the person, you can see whether the code, easy to read, easy to understand, elegant code always adhere to certain specifications, this article on the use of several namespaces, the use of good, can be beneficial to the development of many people, modular code, code decoupling has a certain role!

Let's take a look at the wrong example:

// define some data var name = "Ukerxi"; var version = "1.0.0"; var hobby = "Riding"= ' Test '= ' Test '= ' Test ';

Use namespaces for refactoring:

var men = {  ' ukerxi ',  ' 1.0.0 ',  ' riding '}//  sessionstorage.message = json.stringify ({  ' test ',  ' test ',  ' Test ',});

After refactoring, only two global variables are generated, reducing the probability of naming collisions, and the use of global variables must be minimized, especially when a single page is started, and the use of local storage such as sessionstorage is more noticeable, as they can be accessed between multiple pages, creating a naming conflict A more specific introduction to the use of several namespaces:

One, the use of a single object to wrap (singleton mode)

var myObj = {    "ukerxi"function{   // do something };

Multi-person development, you can name an object according to their own names, and then write their own variables and functions are placed in the namespace, so as to avoid conflict with others, in the actual development, you will also encounter multiple files to share a namespace, you can use the namespace detection, avoid duplication or overwrite;

// Method One if (typeof myObj = = = "undefined") {    var myObj = {};} // method Two (recommended) var myObj = MYOBJ | | {};

When you just want to expand on a namespace, like, extend the plug-in, expand in the Jquery.extend () method;

var myobj= (function(o) {        //  Implement Extended Properties function        return   || {});  // A must or an overhead object in order to use the error caused in the absence of a prior declaration

Second, the closure of the implementation of the variable package, reduce global variables

varMYOBJ = (function () {    //Private Variables    varName = "Ukerxi"; //returns the Get method    return{getName:function () {            returnname; }    };} ());//can be adapted to a more generic namespacevarCommonobject = (function(){    var_data ={name:"Ukerxi", Version:"1.0"    }    //return to Get/set method    return{get:function(key) {return_data[key]; }, set:function(key, value) {//detects if there is a value to set in the original data, so it does not add new data            //If you want to add new data, this sentence can be added without            if(typeof_data[key]! = "undefined") {_data[key]=value; }Else{                return false; }        }    }}());

The return getter, setter method to read and set the value, so that you do not have to worry about variable naming conflicts;

Third, using constructors & prototyping methods, you can construct a more powerful namespace

functioncommonobj (name) {//Private Variables    //There is no need to define an internal _name variable here, because the parameter is also a private variable    var_name =name; //Common Methods     This. GetName =function () {        return_name; };} Commonobj.prototype= (function () {    //static private variables, all instance methods share this data    var_static = "Static"; //     return{getstatic:function () {            return_static; }    };} ());varNewObj1 =NewCommonobj ("Obj1");varNewObj2 =NewCommonobj ("Obj2");//Test OutputConsole.log (Newobj1.getname ());//--"obj1"Console.log (Newobj2.getname ());//--"Obj2"Console.log (newobj1.getstatic);//--"Static"Console.log (newobj2.getstatic);//--"Static"

Finally, each instantiation of the Commonobj constructor can be assigned, but the properties on the prototype are shared, and the code appears to be scattered, which can be further improved;

varCommonobj = (function () {    //Static Private variables    var_static = ""; function_FN (name) {//Common Methods         This. GetName =function () {            returnname;    }; }        //defining a prototype method_fn.prototype ={getstatic:function () {            return_static; }    }    //returns the true constructor    return_FN; }());varNewObj1 =Newcommonobj ();varNewObj2 =Newcommonobj ();//Test OutputConsole.log (Newobj1.getname ());//--"obj1"Console.log (Newobj2.getname ());//--"Obj2"Console.log (newobj1.getstatic);//--"Static"Console.log (newobj2.getstatic);//--"Static"

Iv. static and non-static calls to functions

The main characteristic is that the property defined by the class itself is not owned and inherited by the instantiated function, so it can also be regarded as a namespace, and the subsequent combination of the "builder" mode of the design pattern can create a powerful form of application;

//constructor FunctionvarMYOBJ =function(name) { This. Name =name;};//Static MethodsMyobj.getname =function() {Console.log ("Test");};//Prototyping MethodsMyObj.prototype.getName =function() {Console.log ( This. name);};//Static CallMyobj.getname ();//"Test"//Instantiation callsvarfn =NewMYOBJ ("Ukerxi"); Fn.getname (); //UkerxiA special form of self-executing naming

V. Finally introduce a special self-executing method to form a namespace

var Commonobj = ({    function() {console.log ("test");},    "Ukerxi",      function() {        Console.log (this. Name);         return  This ;    }}). Init ();

The above example is equivalent to creating a new object, then executing the Init method, and finally returning this point to the object, and finally commonobj contains a reference to the new object;

Conclusion

Series of articles, including the original, translation, reprint and other types of articles, on the one hand for their own summary, on the other hand pages want to share knowledge, technical input, but also output, to go further! The article is based on his own practice, reading and understanding, if there are unreasonable and wrong place, please the big guys commented that in order to correct, thanks!

JavaScript Namespaces and usage (front-end basic series)

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.