Javascript design pattern-basic for Object-Oriented Learning

Source: Internet
Author: User

Singleton)

A unit is created when a script is loaded. It organizes a series of associated variables and methods into a logical unit. The content in the logical unit is accessed through a single variable;

A monomer is mainly divided into three parts.

Entry variable used to access internal information (for example, Sky)
Attribute (for example, nickName/age/timeInfo)
Method (for example, sayHello)

Basic Structure

Copy codeThe Code is as follows:
Var Sky = {

/*
* Function 1: Variable Management
*/

NickName: "sky ",
Age: "26 ",

/*
* Role 2: loading initialization Variables
* Execute and initialize Sky.info during the loading process.
*/

TimeInfo: function ()
{
Var _ year = new Date (). getFullYear ();
Return _ year;
}(),

/*
* Role 3: function management, making your functions look less dispersed
*/

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

}
// All internal information is accessed through the Sky variable;
Alert (Sky. timeInfo );


The following is a more detailed description. After reading this article, I believe you should know about it. There are many excellent js writing methods on the Internet, and the single mode is very common.

A single object is an object used to divide the namespace and organize a batch of related attributes and methods together. If it can be instantiated, it can only be instantiated once.
The single mode is one of the most basic but useful modes in javascript.
Features:

You can divide namespaces to clear the risks caused by global variables.
. Use the Branch Technology to encapsulate the differences between browsers.
The code can be organized into one for easy reading and maintenance.

Basic Structure of a monomer (written correctly ):

Copy codeThe Code is as follows:
/* Basic Singleton */
Var Singleton = {
Attribute1: true,
Attribute2: 10,
Method1: function (){},
Method2: function (){}
};

Namespace Division:
Copy codeThe Code is as follows:
Var box = {
Width: 0,
Height: 0,
GetArea: function (){
Return this. width * this. height; // access to objects in js must be displayed, that is, this cannot be omitted.
},
Init: function (w, h ){
// Width = w;
// Height = h; this method is equivalent to defining two global variables (the variable without var declaration is a global variable)
// It is not a value for the width and height of the object.
// The following is correct
This. width = w;
This. height = h;
}
} // Box divides a namespace. the variables in the namespace are only valid in the space.

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

We continue:
Copy codeThe Code is as follows:
Var box = {
Width: 0,
Height: 0, // variable of the monomer
GetArea: function (){
Return width * height; //, width and height are not a single variable, but a global variable defined in init.
}
Init: function (w, h ){
Width = w;
Height = h;
}
} // In init, width and height are not monomer variables.
Window. onload = function (){
Var init = box. getArea ();
Alert (init );
}

Because the width and height values in init are not initialized, an error is reported. Change the value as follows:
Copy codeThe Code is 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 );
}

Yes. Because the width and height used by init and getArea are not all the variables of the monomer, but a global variable, we can call them without being affected.

If we write it like this, we can better understand:

Copy codeThe Code is as follows:
Var box = {
Width: 0,
Height: 0,
GetArea: function (){
Return width * height; // access to objects in js must be displayed, that is, this cannot be omitted.
},
Init: function (w, h ){
Width = w;
Height = h;
}
} // The width and height here are not actually single objects.
Window. onload = function (){
Width = 0;
Height = 0;
Var width = box. getArea ();
Alert (width );
}

In this way, an error is reported. We can see that the above method does not create a namespace for global variables, and global variables pose a risk to us. So the top line is correct. Let's verify it:
Copy codeThe Code is as follows:
Var box = {
Width: 2,
Height: 2,
GetArea: function (){
Return this. width * this. height; // access to objects in js must be displayed, that is, this cannot be omitted.
},
Init: function (w, h ){
This. width = w;
This. height = h;
}
}
Window. onload = function (){
Width = 0;
Height = 0;
Var width = box. getArea ();
Alert (width );
}

It can be seen that the width and height in window. onload do not interfere with each other, because the width and height in the monomer create a namespace.

Member attributes:

After discussing the namespace, let's set the attributes of the single variable and method. Anyone who has studied other languages (java, c ++, c #...) should be familiar with the public and private attributes of class members,
Although there is not such a strict object-oriented (oop) in javascript, we can use closures to simulate it. After all, it is difficult to set some variables to public.

Copy codeThe Code is as follows:
Var circle = (function (){
// Pravite member!
Var r = 5;
Var pi = 3.1416; // use a semicolon
Return {// public member
GetArea: function (){
Return r * pi; // do not add this to private members.
}, // Use a comma
// If you want to change the values of r and pi, you can only set a public function.
Init: function (setR ){
R = setR;
}
}
})()
Window. onload = function (){
Circle. r = 0; // Private Members cannot be accessed, which is equivalent to creating a common member r for circle.
Alert (circle. getArea ());
Circle. init (0); // you can access it through public tool functions.
Alert (circle. getArea ());
};

Private variables and methods are read-only, and public variables and methods are readable and writable.
Access:
You can directly access private members without any modification,
For public access, add "this." Before the single scope, and add "circle." (single name.) outside the single scope .)

Haha, it seems a bit delicious!
. Use the Branch Technology to encapsulate the differences between browsers
Note:
A must use a closure to implement real-time binding.
B. Each branch is separated by a semicolon.
C returns the branch name.
Use the single name + branch method name when calling;
Copy codeThe Code is as follows:
// The XHR (XMLHttpRequest) object is defined using the single branch technology. It must be implemented using a closure.
Var XHR = (function (){
// The three branches
Var standard = {
CXHR: function (){
Return new XMLHttpRequest ();
}
};
Var activeXNew = {
CXHR: function (){
Return new ActiveXObject ('msxml2. xmlhttp ');
}
};
Var activeXOld = {
CXHR: function (){
Return new ActiveXObject ('Microsoft. xmlhttp ');
}
};
// To assign (assign) the branch, try each method; return whatever doesn't fail
Var testObject;
Try {
TestObject = standard. cXHR ();
Return standard; // return this branch if no error was 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, I would like to say a few more words:
It is said that a single person is one of the most commonly used models. As for the advantages and disadvantages, you must gradually understand it in practice. Because I am also a beginner, I do not have much say, and I still forget to give 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.