The single mode of JavaScript---design pattern

Source: Internet
Author: User

A single body is an object that divides a namespace and organizes some related properties and methods together, and if she can be instantiated, it can only be instantiated once (she can only marry once, not married).

The monomer mode is one of the most basic but also the most useful patterns in JavaScript.

Features: 1. can be used to partition namespaces to clear the danger or impact of global variables.

2. Use branching technology to encapsulate the differences between browsers.

3. The code can be organized into a more integrated, easy to read and maintain.

The basic method of the monomer pattern:

/**/var her =   {' Anna ',   ' Women ',     function() {        //  Some processing logic ...    },    function () {        //  Other processing functions ...     }      }
1. Partitioning namespaces:
varbox ={width:0, Height:0, Getarea:function(){         return  This. Width * This. width;//JS in the object into the access must be displayed, that is, this is not omitted}, Init:function(W, h) {//width = w;         //height = h; This is equivalent to defining two global variables (variables declared with no var are global)         //is not an assignment to the width and height of an object         //The following are the correct          This. width =W;  This. Height =h; }}//box divides a namespace, and the variables in the namespace are only valid in space

All the members and methods in the above monomers are public, that is, they can be arbitrarily changed outside the monomer (but cannot access the local variables), why is it that the monomer provides a namespace?

Don't worry, we'll look down:

varbox ={width:0, Height:0,//variables of the monomerGetarea:function(){            returnWidth * height;// Width,height is not actually a single variable, but a global variable defined in init} init:function(w,h) {width=W; Height=h; }}// Width,height in Init is not actually a single variableWindow.onload =function(){    varinit =Box.getarea (); Alert (init);}

Because the width,height in Init is not initialized, an error is made, so change it:

varbox ={width:0, Height:0, Getarea:function(){            returnWidth *height; }, Init:function(w,h) {width=W; Height=h; }}window.onload=function() {width= 0; Height= 0; //or Box.init (0,0);        varinit =Box.getarea (); Alert (init);}

It is possible, because the width and height used by init and Getarea are not variables that are owned by the monomer, but a global variable, so we can make arbitrary calls outside of the monomer without being affected,

varbox ={width:0, Height:0, Getarea:function(){            returnWidth * height;//JS in the object into the access must be displayed, that is, this is not omitted}, Init:function(w,h) {width=W; Height=h; }    }//the width,height here is not actually a monomer object.Window.onload =function() {width= 0; Height= 0; varwidth =Box.getarea (); alert (width);}

This will be an error, it can be seen that the way we do not create a namespace for global variables, global variables pose a danger to us. So the most up-to-the-minute notation is right, so let's verify that:

varbox ={width:2, Height:2, Getarea:function(){            return  This. Width * ThisThe access to objects in the. height;//js must be displayed, that is, this is not omitted}, Init:function(w,h) { This. width =W;  This. Height =h; }}window.onload=function() {width= 0;//does not affect local variables in the monomer, which is the namespace height= 0;//does not affect local variables in the monomer, which is the namespacevarwidth =Box.getarea (); alert (width);}

It is apparent that the width and height in the window.onload have no interference because the monomer establishes a namespace for width and height in the monomer.

2. Properties of the member:

Although there is not such a strict object-oriented (OOP) in JavaScript, we can use closures to do a simulation, after all, some variables are set to public is very bad.

varher = (function(){    varname = ' Anna '; varSex = ' Women '; return{getarea:function(){             returnName + ' is a ' +sex; }, Init:function(b) {name=b; }}) (); Window.onload=function() {her.name= ' Jock ';//Cannot accessalert (Ger.getarea ()); Her.init (' Lous '); Alert (Her.getarea ());}

Private variables, methods are read-only, public variables, methods are readable and writable.

Access:
For private members, direct access to the front without adding any decorations,
For public access, add "this." in front of the monomer scope, and add "her" to the field before the monomer. (Monomer name.)

3. Using branching technology to encapsulate differences between browsers

Note the place:

A. Be sure to use closures for instant binding

B. Separate each branch with a semicolon

C. Last returned is the name of the branch

D. Call the name of the method with the name of the monomer + branch;

//the XHR (XMLHttpRequest) object is defined using the branching technique of the monomer, which must be implemented with closures .varXHR = (function(){    //The three branches    varStandard ={cxhr:function(){                return NewXMLHttpRequest ();    }        }; varActivexnew ={cxhr:function(){                return NewActiveXObject (' Msxml2.xmlhttp ');    }        }; varActivexold ={cxhr:function(){                return NewActiveXObject (' Microsoft.XMLHTTP ');    }        }; //to assign (allocated) the branch, try each method;return whatever doesn ' t fail    varTestobject; Try{testobject=standard.cxhr (); returnStandard//return this branch if no error is thrown}Catch(e) {Try{testobject=activexnew.cxhr (); returnactivexnew; }Catch(e) {Try{testobject=activexold.cxhr (); returnActivexold; }Catch(e) {Throw NewError (' Create the Xmlhttprequestobject failed! '); }}}) (); Window.onload=function() {alert (XHR.CXHR ());}

Let's make progress together!!! It's Friday, anyway.

The single mode of JavaScript---design pattern

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.