JavaScript single-case mode

Source: Internet
Author: User

The singleton mode is also known as the monomer mode.

1, the monomer pattern is used to create namespaces, to organize the properties and methods associated with the series into a single logical unit, reducing global variables.
The code in the logical unit is accessed through a single variable.

2, three features:
① There is only one instance of the class;
② The class creates the instance itself, creating its own instance object inside the class;
③ exposes this instance interface to the entire system

There are four basic forms of the monomer pattern:

The first, simplest monomer, is instantiated only once I précis-writers as a JSON object

(1) Basic structure

var userinfo={// has been instantiated by itself  is actually a JSON object        name:" test name " ,        Dept:" test pd",        code:" test PD001  ",        getname:function () {            return" test "         }    };

(2) Use the same method as JSON: Use Point "." The way to access

Alert (Userinfo.getname ())

The monomer pattern is used to divide the namespace, and a brief introduction of a group of related properties and methods is organized:

 varcomm={};//an empty object

comm.userinfo={//the first namespace under an empty objectName"named Space 1.", Code:"001" }
Comm.funcinfo={//the second namespace under an empty objectFuncName:"named Space 2.", Code:"002" }

Summary: This way you can see that the object's variable value is not dynamically loaded, and the object does not display initialization, thus having a second monomer mode.

Second, monomers with local variables

Requirements: Simulates a process that uses AJAX to load data from a database

(1) Simple simulation of the AJAX process

// simulating an AJAX operation     function Ajax () {};//null object     // static function  impersonation as ajax.request= from the database where values  are written dead    function (URL,FN) {        // default always callback succeeded        if(true) {            fn (" test value 1"," test value 2")        }    }

(2) In the simplest monomer appears in the data is not dynamically loaded from the database, and does not show the instantiation of the object, where the closure principle to solve the above problems

//using closures to solve the problem: dynamically loading data from the database, showing instantiation    varuserinfo=(function () {//(1)using closures to make monomers have their own private local variables        varName=""; varCode=""; //(2)accessing a database using AJAX to fetch dataAjax.request (the URL", Function (n,c) {//due to simply passing parameters in the simulated Ajax, the first parameter can be any name=N; Code=C; })        //(3)the assignment of a private variable to a single implementation        return{name:name, Code:code}}) ()

(3) Using this method of monomer, without instantiation can be directly returned to a monomer "because of the use of userinfo, directly return a monomer back"

alert (userinfo.name);

Summary: Advantages, flexibility

Drawback: Return monomer data volume is large, you need to fetch data from the database, each load to execute, will affect program performance.

Since each load is executed directly, the return monomer data volume will affect the performance of the rendering, so there is a third mode of monomer.

Thirdly, the solution provided by the inert monomer is: when the method is instantiated, it is not executed at the time of loading.

Then on the basis of the second change to

(1) Simulating Ajax loading data from a database unchanged

// simulating an AJAX operation     function Ajax () {}    // static function  impersonation as a value from the database    ajax.request=function (URL, fn) {        // default always callback succeeds        if(true) {            fn ("  Test value 1"," test value 2")        }    }

(2) Dynamically loading data from the database, displaying instantiation, using a function (init ()) to encapsulate the function that produces the monomer, returning the function by a private variable (init ())

 //using closures to solve the problem: dynamically loading data from the database, showing instantiation    varuserinfo=(function () {
var userinfo=""; // Private Variables function Init () {//in the resulting monomer mode for the Wrap layer initialization function//using closures to make monomers have their own private local variables varName=""; varCode=""; //accessing a database using AJAX to fetch dataAjax.request ("URL", Function (n,c) {name=N; Code=C; }) //Monomer return{name:name, Code:code,}} return {//At this point the initialization function is called to implement the monomer Generation Getinstance:function () { if(use Rinfo) {//userinfo= "" is false return userInfo; }Else {userInfo=Init (); return UserInfo; } } } })()

(3) Use Access to the UserInfo object inside the Get initialization function that gets the object (getinstance ())

   Alert (Userinfo.getinstance (). name);

Summary: The use of inert monomers is essentially through the function of the resulting monomer once again encapsulated (using the function encapsulation), and then through the class provided by the unique interface (getinstance () method) to access the initialization of the monomer function.

Fourth, branching monomers

Simple use: When doing Ajax, you get different XHR based on different browsers. (Encapsulate differences between browsers into dynamic methods, which are useful for resolving differences between browsers.) )

For example, here is a simple example: Initializes a different interface at the same computer resolution. (This is just a pop-up window display)

(1) Get the computer's resolution

// get the machine's resolution    var screenwidth=window.screen.width; // width    var screenheight=window.screen.height; // Height

(2) Conduct branch judgment processing to encapsulate the difference in a dynamic method

  varportalinfo=(function () {
Monomervar$1280_1024={info:'1,2,3,5'}//Monomer 1 var$1366_768={info:'4,2,1,2'}//Monomer 2

Dynamic Graph Selection Browser difference results (here is the resolution)if(screenwidth== the){ return$1280_1024;//return monomer for initialization}Else if(screenwidth==1366){ return$1366_768;//return monomer for initialization}Else { Throw NewError ("Please check your current computer resolution") } })();

(3) Use to get the final result

Alert (portalinfo.info)//My result is 4,2,1,2 this is due to the resolution of my computer is 1366*768

To summarize, there is a disadvantage to branching monomers: In the branch, monomer 1 and monomer 2 are created, and stored in memory, but only one.

You need to choose between calculating time and consuming memory.

JavaScript single-case mode

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.