JavaScript design pattern __java

Source: Internet
Author: User
Tags closure

Turn from: http://www.cnblogs.com/Darren_code/archive/2011/08/31/JavascripDesignPatterns.html


have been considering this month to share what things best, the original plan is to write some HTML5 in the content of JS or Ajax, but their ability to express, time, and personal work aspects of the problem, this is still waiting for the next month to share it ^.^.

The old rules, the beginning of the text before the first account of the purpose of writing this article and some considerations:

1. First I have been engaged in front-end development, so in addition to JavaScript other languages do not understand deeply, so the article will only be JavaScript language perspective to prove;

2. In fact, I personally used in the project is not much of the model, the understanding of the concept of the model is not so abstract, so recently in the interview if the interviewer asked the model-related issues, their feelings in the process of the answer is very depressed, a lot of things are not clear, so they find some relevant information, will have this article to share;

3.JavaScript mode and front-end work and growth are inseparable, because this is not a simple topic, so I can only try to use simple expressions and examples to illustrate, and the garden has a lot of experts, so I hope everyone enthusiastically speak (due to the level of limited, please give a lot of advice, hope the mouth lenient);

4. Since this article is more just a reminder of the role of an introduction and explanation, do not intend to do a detailed analysis of each model, so each mode only use one to two examples, may cause the expression of this example is not optimal or not comprehensive, if you reader feel not enjoyable, you can go to find relevant information;

5. Do anything to adhere to, write a blog is the same, hehe, at least one month (the article is indeed longer, I hope to be able to help friends, the focus of the introduction in the Foreword, we can choose the mode of interest in depth ).

6. Welcome reprint, but please indicate the source, thank you.

Learn about JavaScript design patterns We need to know some of the necessary knowledge points: (content relative to the base, master please skip)

  closures: about closures this month in the garden has a few good share, in this I also from the most practical place, to say my understanding.

1. The most common way to close a package is to return an inline function (what is an inline function). is a function declared inside a function);

2. In JavaScript there are scopes and execution environments where variables inside a function are inaccessible outside of the function, and global variables are available within the function. For a variety of reasons, we sometimes need to get the variables inside the function, but not in the normal way, then we can create a closure to access the variable externally.

3. The purpose of closure is mainly to read the function internal variables mentioned above, there is also a role is to keep these variables in memory.

4. Use closures to note that because variables are saved in memory, memory is consumed, so the closure cannot be abused. The workaround is to remove all unused local variables before exiting the function.

Finally, a set of closure code, so more intuitive.

1 function f () {
 2   var n = 999;
 3   Function F1 () {
 4    alert (n+=1);
 5  }
 6 return  F1;
 7}
 8 var result = f ();
 9 result (); 1000
();//1001 result
();//1002


  encapsulation: by declaring a method or attribute as private, you can keep the object's implementation details secret to other objects to reduce the coupling between objects, preserve the integrity of the data and constrain its modification, which can be more reliable and easier to debug. Encapsulation is the cornerstone of object-oriented design.

Although JavaScript is an object-oriented language, it does not have any internal mechanism to declare members as public or private, so we can only find ways to do that. Below or through a complete set of code to analyze, describes what is private properties and methods, what is the privileged properties and methods, what is public properties and methods, what is public and static properties and methods.

private Properties and methods: functions are scoped, variables declared in functions with the VAR keyword are not accessible externally, and private properties and methods are essentially variables that you want to be inaccessible outside the object.

privileged properties and methods: The This keyword used when creating properties and methods, because they are defined in the scope of the constructor, so they can access private properties and methods, and only those methods that require direct access to private members should be designed as privileged methods.

common Properties and methods: properties and methods that are directly linked to the prototype, do not have access to private members within the constructor, can access privileged members, and subclasses inherit all common methods.

Total Static Properties and methods: the best way to understand this is to think of it as a namespace, which is actually equivalent to using a constructor as a namespace.

1/*--encapsulation--* *
 2 var _packaging =function () {
 3    //private properties and Methods
 4    var name = ' Darren ';
 5    var method1 =function () {
 6  //...
 7    }
 8    //Privileged properties and methods
 9    this.title = ' JavaScript design Patterns ';    this.getname =function () {One
return  name;
14//Total static properties and methods
_packaging._name = ' Darren code ';
_packaging.alertname =function () {    alert (_packaging._name);
19//Common properties and methods
_packaging.prototype = {    init:function () {//       ...
24}    


  Inheritance : inheritance is an abstract topic in itself, and inheritance is a complex topic in JavaScript, because JavaScript wants to implement inheritance in two ways, namely, class inheritance and prototype inheritance, each of which requires a lot of action, I'll explain this very important topic in JavaScript by analyzing the examples below.

 1/*-Class inheritance-*/2//First declare a superclass 3 function person (name) {4 this.name = name;
 5} 6//Add method to the prototype object of this superclass GetName 7 Person.prototype.getName =function () {8 returnthis.name;
9} 10//Instantiate this superclass one var a =new person (' Darren1 ') alert (A.getname ()); 
13//Then declare the class function programmer (name,sex) {15//class to invoke the constructor of the superclass person and pass the parameter name to its person.call (this,name);
This.sex = sex;
18} 19//The prototype object of this subclass equals the instance of superclass Programmer.prototype =new person (); 21//Because the subclass's prototype object equals an instance of the superclass, so prototype.constructor This method is also equal to the superclass constructor, and you can test it yourself, without this step, alert (
Programmer.prototype.constructor), this is a reference to the person superclass, so to the new assignment for their own Programmer.prototype.constructor = programmer; 23//subclass itself adds the Getsex method Programmer.prototype.getSex =function () {returnthis.sex; 26} 27//instantiate this subclass V
AR _m =new programmer (' Darren2 ', ' Male ');
29//Own Method alert (_m.getsex ()); 31//The method of inheriting the superclass alert (_m.getname ()); 

Code is not difficult, as long as the prototype chain has a basis to understand. The class-style inheritance pattern is the primary pattern of JavaScript inheritance, which is used in almost all JavaScript code written in object-oriented fashion, and because only JavaScript uses archetypal inheritance in a variety of popular languages, it is best to use class inheritance. But to be familiar with the JavaScript language, prototype inheritance is what we have to understand, and whether or not you use it in your project depends on your personal coding style.

1/*--Prototype Inheritance--*/
 2//clone () function is used to create a new class Person object
 3 var clone =function (obj) {
 4 var _f =function () {};
  
   5    
   //This is the core of the prototype inheritance, the prototype object of the function is object literal
 6    _f.prototype = obj; 
 7    returnnew _f;
 8}
 9//First declare an object literal
of var person = {One    name: ' Darren ',    getname:function () {
   
    13 Returnthis.name; 16//You do not need to define a subclass of person, as long as you perform a clone of var programmer = Clone (person); 18//You can directly obtain the default value provided by person, or you can add or modify properties and Methods (Programmer.getname ()) programmer.name = ' Darren2 ' alert (Programmer.getname ()) 23//Declare subclass, execute a clone can be var Someone = Clone (programmer);  
   
  


------------------------------------------The text begins, I am the split line------------------------------------------

Preface:

The role of JavaScript design patterns-improves code reusability, readability, and makes code easier to maintain and extend.

1. Monomer mode, Factory mode, bridge mode the individual believes that this is an excellent front-end must master the model, both abstract programming and interface programming are very good.

2. There are many similarities between the decorator pattern and the combination pattern, which implement the same interface as the wrapped object and pass the invocation of any method to those objects. Decorator mode and combination mode is I describe the more difficult two models, I personally have not used, so check a lot of relevant information and documents, please Haihan.

3. Facade mode is a very interesting model, almost all JavaScript libraries will use this pattern, if you have a reverse thinking or reverse programming experience, you will be easier to understand the pattern (sounds challenging, in fact, a contact you know it is a very simple model) There is also the configuration model and the façade mode to take, this mode of the existing interface packaging, reasonable use can improve the development efficiency to a large extent. These two patterns have similarities, so a piece of understanding is believed to be quick.

4. The meta pattern is a model for optimization purposes.

5. Agent mode is primarily used to control access to objects, including the postponement of the instantiation of classes that require a large amount of computational resources to be consumed.

6. The Observer pattern is used to observe the state of an object and to be notified when it is changed. Lets an object listen to the event to respond to it. The Observer pattern is also referred to as "subscriber mode."

7. The command mode is a way to encapsulate method calls, using named patterns to Parameterize and pass the method calls, and then execute them when needed.

8. The responsibility chain pattern is used to eliminate the coupling between the sender and receiver of the request.

What are the JavaScript design patterns?

  monomer (Singleton) mode: It is definitely the most basic and useful pattern in JavaScript.

The monomer is used in JavaScript for a variety of purposes, and it uses it to divide namespaces . You can reduce the number of global variables in a Web page (there is a risk of using global variables in Web pages), you can avoid code conflicts (using reasonable namespaces), and so on when multiple people develop.

In small or medium projects or functions, a monomer can be used as a namespace to organize its own code in a global variable name; in slightly larger or more complex functions, the monomer can be used to organize the related code together for good maintenance later.

The way to use a monomer is to use a namespace that contains all of your code's global objects, examples:

1 var functiongroup = {
2 name: ' Darren ',
3 method1:function () {
4//code
5},
6 Init:function () {
7//code
8}
9}

Or

1 var functiongroup  =newfunction MyGroup () {
2 this.name = ' Darren ';
3 This.getname =function () {
4 returnthis.name
5}
6 this.method1 =function () {}
7 ...
8}

   

  Factory (Factory) mode: provides an interface to create a series of related or interdependent objects without specifying their specific classes.

A factory is the task of transferring the creation of a member object to an external object, which is the benefit of eliminating coupling between objects (what is coupling). is mutual influence). by using the factory approach instead of the new keyword and the specific class, all instantiated code can be concentrated in one place , helping to create modular code, which is the purpose and advantage of the factory model.

For example: You have a large function to do, some of which are to consider extensibility, then this part of the code can be considered abstract, as a new object to do processing. The benefit is that it's easy to maintain in the future-it only needs to manipulate the internal methods and attributes of the object to achieve the goal of dynamic implementation. A very famous example-the xhr factory :

1 var xmlhttpfactory =function () {}; This is a simple Factory mode
 2 xmlhttpfactory.createxmlhttp =function () {
 3 var XMLHttp = null;
 4 if (window. XMLHttpRequest) {
 5 XMLHttp = new XMLHttpRequest ()
 6}elseif (window. ActiveXObject) {
 7 XMLHttp = new ActiveXObject ("Microsoft.XMLHTTP")
 8} return
XMLHttp;
//xmlhttpfactory.createxmlhttp () This method returns a Xhr object based on the specific circumstances of the current environment.
var ajaxhander =function () {
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.