The single mode of JavaScript design pattern Object-oriented learning base _JS object-oriented

Source: Internet
Author: User
monomer mode (singleton)

The monomer is created when the script is loaded, and can organize a series of associated variables and methods into a logical unit, and the contents of the logical unit are accessed through a single variable;

A monomer is mainly divided into three parts

Entry variables for accessing internal information (for example: Sky)
Properties (such as: Nickname/age/timeinfo)
Methods (such as: SayHello)

Basic Structure

Copy Code code as follows:

var Sky = {

/*
* Function one, variable management
*/

Nickname: "Sky",
Age: "26",

/*
* Function Two, initialization variable in load
* Execute and initialize the Sky.info during loading
*/

Timeinfo:function ()
{
var _year = new Date (). getFullYear ();
return _year;
}(),

/*
* Function three, function management, so that your function does not look so scattered
*/

Sayhello:function ()
{
Alert ("hello,world!");
}

}
All internal information is accessed through the variable of sky.
alert (sky.timeinfo);


The following is a more detailed description, after reading this article, I believe you should almost understand, online a lot of master JS writing, monomer mode is very common.

A monomer is an object that is used to partition a namespace and organize a group of related properties and methods together, and if he can be instantiated, he can only be instantiated once.
Monomer mode is one of the most basic but also most useful patterns in JavaScript.
Characteristics:

. You can divide the namespace to clear the risks posed by global variables.
. Use branching techniques to encapsulate the differences between browsers.
. The code can be organized into a more integrated, easy to read and maintain.

the basic structure of the monomer (the correct formulation):

Copy Code code as follows:

/*basic singleton*/
var Singleton = {
Attribute1:true,
Attribute2:10,
Method1:function () {},
Method2:function () {}
};

To divide the namespaces:
Copy Code code as follows:

var box = {
width:0,
height:0,
Getarea:function () {
The access to the object in return This.width*this.height;//js must be displayed, that is, this is not omitted
},
Init:function (w,h) {
width = w;
Height = h; This approach is equivalent to defining two global variables (variables declared without var are global variables)
is not an assignment to the width and height of an object
The following is correct
This.width = W;
This.height = h;
}
}//box divides a namespace in which the variables in the namespace are only valid in space.

All the members and methods of the above monomer are public, that is, they can be arbitrarily altered outside the monomer, so why does the monomer provide a namespace?

We continue:
Copy Code code as follows:

var box = {
width:0,
Variable of height:0,//monomer
Getarea:function () {
In return width*height;//, Width,height is not a single variable, but a global variable defined in init
}
Init:function (w,h) {
width = w;
Height = h;
}
In}//init, Width,height is not a single variable.
Window.onload = function () {
var init = Box.getarea ();
Alert (init);
}

Because the width,height in Init is not initialized, an error is made, so change:
Copy Code code as follows:

var box = {
width:0,
height:0,
Getarea:function () {
return width*height;
},
Init:function (w,h) {
width = w;
Height = h;
}
}
Window.onload = function () {
width = 0;
Height = 0;
or Box.init (0,0);
var init = Box.getarea ();
Alert (init);
}

It's OK, because the width and height used by init and Getarea are not all variables of the monomer, but a global variable, so we can make random calls outside of the monomer without being affected.

If we write this, we will understand better:

Copy Code code as follows:

var box = {
width:0,
height:0,
Getarea:function () {
The access to the object in return Width*height;//js must be displayed, that is, this is not omitted
},
Init:function (w,h) {
width = w;
Height = h;
}
}//here, the width,height is not a single object.
Window.onload = function () {
width = 0;
Height = 0;
var width = Box.getarea ();
alert (width);
}

This writing will be an error, we can see that the above method for global variables did not establish a namespace, global variables for us to pose a danger. So the above wording is right, let's verify:
Copy Code code as follows:

var box = {
Width:2,
Height:2,
Getarea:function () {
The access to the object in return This.width*this.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;
Height = 0;
var width = Box.getarea ();
alert (width);
}

The width and height of the window.onload are no longer disturbed, as the monomer establishes a namespace for the width and height of the monomer.

Properties for members:

After discussing the namespaces, let's set the properties of the monomer variables and methods. A person who has studied other languages (java,c++,c#). Should be aware of the public and private of the class members,
Although there is no such strict object-oriented (OOP) in JavaScript, we can do a simulation with the help of closures, after all, it is not good to have a variable set to public.

Copy Code code as follows:

var circle = (function () {
Pravite member!
var r = 5;
var pi = 3.1416;//followed by a semicolon
Return{//public Member
Getarea:function () {
Return r*r*pi;//access to private members do not add this
},//followed by a comma
If you want to change the value of R and Pi, you can only do this by setting a public function
Init:function (SETR) {
R = Setr;
}
}
})()
Window.onload = function () {
CIRCLE.R = 0;//cannot access private members, equivalent to creating a shared member for Circle R
Alert (Circle.getarea ());
Circle.init (0);//can be accessed through public utility functions.
Alert (Circle.getarea ());
};

private variables, methods are read-only, public variables, methods are readable and writable
Access:
For private members, direct access is not preceded by any modification,
The public access is preceded by a "this." in the monomer scope and preceded by a "circle." (Monomer name.)

Oh, it seems a little taste!
. Use branching techniques to encapsulate differences between browsers
Notice of the place:
A be sure to use closures to achieve instant binding
b separated by semicolons between each branch
C Last return is the name of the branch
D when called with the monomer name + branch method name;
Copy Code code as follows:

Using the branch technology of monomer to define XHR (XMLHttpRequest) objects, you must use a closure to achieve
var XHR = (function () {
The three branches
var standard = {
Cxhr:function () {
return new XMLHttpRequest ();
}
};
var activexnew = {
Cxhr:function () {
Return to new ActiveXObject (' msxml2.xmlhttp ');
}
};
var activexold = {
Cxhr:function () {
Return to new ActiveXObject (' microsoft.xmlhttp ');
}
};
To assign (assigned) the branch, try each method;return whatever doesn ' t fail
var testobject;
try{
Testobject = STANDARD.CXHR ();
Return standard;//return this branch if no error is thrown
}catch (e) {
try{
Testobject = ACTIVEXNEW.CXHR ();
return activexnew;
}catch (e) {
try{
Testobject = ACTIVEXOLD.CXHR ();
return activexold;
}catch (e) {
throw new Error (' Create the Xmlhttprequestobject failed! ');
}
}
}
})();
Window.onload = function () {
Alert (XHR.CXHR ());
}

Finally, a few more words:
For the monomer is said to be one of the most commonly used mode, as for the pros and cons of the experience in the practice of slowly, because I am also a beginner, so there is not too much say, not enough to point out also forget master advice
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.