Exploration of JavaScript design patterns [1]

Source: Internet
Author: User

During this period of time, I had no time to read the in-depth understanding of the Javascript series by Uncle Tom, a blogger in the blog Park. It was also rewarding because the interview was approaching, I feel that my only advantage may be JavaScript, so I stepped up and went to the library to borrow a javascript design pattern, a thin book, and put it on the shelf, which was quite inconspicuous, on the shelf, various well-dressed JavaScript books are all messy. They only see the four big words of the design pattern, so I borrowed them, at the beginning, I simply flipped through one or two chapters at random, and it gave me a sense of openness, far better than the seemingly awesome books on the shelves, now the taste of reading is a little bit embarrassing. How about reading a book? You can feel it by turning it over. Later, it was Turing.ProgramDesign Series, I think foreigners are really awesome, and that translation is also very useful, some places are very careful, I recommend the Javascript design model --- Ross harmes Dustin Diaz

Now I also found a problem. If I don't take notes on the books I read, I will not be impressed after a while, but I am a little used to reading the books and then summing up my blog posts, I will share with you the practices. In fact, the path to becoming a javascript bull is rather rugged. I personally feel that it is more difficult than to become a C ++/Java path, because of the positioning of the script language, it is not realistic to let it implement complicated logic functions. Even if it is available, it is not easy to access. In addition, due to its flexibility, therefore, it is not that easy to control. In general, you need experience and a platform. Aren't other linguistics tired? If you are tired, the language doesn't mean anything. You need to think more deeply, such as design patterns. Of course, a cainiao like me still has a long way to go. Come on, And come step by step. There is always a time to climb high.

View code

 // 1. The simplest and most common way to complete tasks in Javascript  Function  Startanimation (){...}  Function  Stopanimation (){...}  //  2. Use prototype  VaR Anim = Function  () {...}; Anim. Prototype. Start = Function  () {...} Anim. Prototype. Stop = Function (){...}  //  3. encapsulate the class definition in a declaration.  VaR Anim = Function  () {...} Anim. Prototype = {Start: fucntion () {...}, stop:  Function  (){...}};  //  4. Use function. Prototype. Method to add a new method to the class. Function. Prototype. method = Function  (Name, FN ){ This . Prototype [name] = FN ;};  VaR Anim = Function  () {...}; Anim. Method ( 'Starrt ', Function  () {...}); Anim. Method ( 'Stop ', Function  (){...});  //  5. chained call Function. Prototype. method = Function  (Name, FN ){  This . Prototype [name] = FN;  Return   This  ;};  VaR Anim = Function  () {...}; Anim. Method ( 'Starrt ', Function  () {...}). Method ( 'Stop ', Function  (){...}); 

I don't know.CodeWhat are your feelings? I think it's amazing. I have learned grammar or something, but I never thought it could be used. Especially the fifth type. If you remember well, jquery should use this method in a large number of chained calls.

1 Interface

Three methods for simulating interfaces in javascript: annotation, attribute checking, and duck-style distinguishing

1.1 annotation Method --The annotation method is the simplest, but the effect is the worst. It only adds a comment, which has no impact on performance, but no error check.

View code

 /*  Interface Composite {function add (child); function remove (child); functiongetchild (INDEX);} interface formitem {function save ();}  */  VaR Compositeform = Function (ID, method, Action ){ //  Iimplements composite, formitem  ...}; //  Implement the Composite Interface Compositeform. Prototype. Add = Function  (Child) {...}; compositeform. Prototype. Remove = Function  (Child) {...}; compositeform. Prototype. getchild = Function  (Index ){...};  //  Implement the formitem Interface Compositeform. Prototype. Save = Function  (){...}; 

1.2 property check imitation interface --All classes explicitly declare the interfaces they have implemented. Any function that requires the class commitment to belong to a specific type can check this attribute, an error is thrown when the required interface is not declared, but this method does not ensure that the class actually implements the self-implemented interface. Some additional work is required, slightly affecting the performance.

View code

 /*  Interface Composite {function add (child); function remove (child); functiongetchild (INDEX);} interface formitem {function save ();}  */  VaR Compositeform = Function  (ID, method, Action ){  This . Implementsinterfaces = ['composite ', 'formitem' ];...}; Function  Addform (forminstance ){  If (! Implements (forminstance, 'composite ', 'formitem' )){  Throw   New Error ("object does not implements a required interface :" );}}  //  The implememts function, which checks to see if an object declares that it  //  Implements the required interfaces.  Function Implements (object ){  For ( VaR I = 1; I <arguments. length; I ++ ){  VaR Interfacename = Arguments [I];  VaR Interfacefound = False  ;  For ( VaR J = 0; j <object. implementsinterfaces. length; j ++ ){  If (Object. implementsinterfaces [J] = Interfacename) {interfacefound = True  ;  Break  ;}}  If (! Interfacefound ){  Return   False  ;}}  Return   True  ;} 

1.3 duck-style imitation interface --It doesn't matter whether the class declares which interfaces it supports, as long as it has methods in these interfaces. Definition: if an object has all methods with the same name as the method defined by the interface, you can determine that the object implements this interface.

View code

 //  Interfaces  VaR Composite = New Interface ('composite ', ['add', 'delete', 'getchild' ]);  VaR Formitem = New Interface ('formitem ', ['save' ]);  //  Compositeform class  VaR Compositeform = Function  (ID, method, Action ){...};  Function  Addform (forminstance) {ensureimplements (forminstance, composite, formitem );}  //  The ensureimplements function requires at least two parameters. The first parameter is the object to be checked, and the other parameters are interfaces for checking the object. 

1.4 specific implementation method ---Combining the first and third methods, you can use annotations to declare interfaces supported by the class to improve code reusability and document integrity. We also use the auxiliary class interface and its class method interface. ensureimplements to explicitly check the methods implemented by the object.

View code

 //  Interfaces  VaR Composite =New Interface ('composite ', ['add', 'delete', 'getchild' ]);  VaR Formitem = New Interface ('formitem ', ['save' ]);  //  Compositeform class  VaR Compositeform = Function  (ID, method, Action ){...};  Function  Addform (forminstance) {ensureimplements (forminstance, composite, formitem );} VaR Interface = Function  (Name, methods ){  If (Arguments. length! = 2 ){  Throw   New Error ("interface constructor called with:" + arguments. Length + "arguments, but expected exactly 2 ." );}  This . Name = Name;  This . Methods = [];  For (VaR I = 0, Len = methods. length; I <Len; I ++ ){  If ( Typeof Methods [I]! = 'String' ){  Throw   New Error ("interface constructor expects method names to be passed in as a string ." );}  This  . Methods. Push (methods [I]) ;}}; interface. ensureimplements = Function  (Object ){ If (Arguments. Length <2 ){  Throw   New Error ("function interface. ensureimplements called with" + arguments. Length + "arguments, but expected at least 2 ." );}  For ( VaR I = 1, Len = arguments. length; I <Len; I ++ ){  VaR Interface = Arguments [I];  If (Interface. constructor! =Interface ){  Throw   New Error ("function interface. ensureimplements expects arguments two and above to be instances of interface ." );}  For ( VaR J = 0, methodslen = interface. Methods. length; j <methodslen; j ++ ){  VaR Method = Interface. Methods [J];  If (! Object [Method] | Typeof Object [Method]! = 'Function'){  Throw   New Error ("function interface. ensureimplements: object does not implement the" + interface. Name + "inerface. Method" + method + "was not found ." );}}}}; 

1.5 summarize whether the interface is required

Benevolent wise, there is no need to use small and less time-consuming projects. You can also simplify the implementation. Use the public interface. js file to remove all explicit checks on the constructor and replace the original constructor check with interface. ensureimplements.

2 encapsulation and Information Hiding

There are three basic modes for creating objects in JavaScript. A wide-open portal uses underscores to indicate private methods and attributes, and closures to create real private members.

2.1 wide-open portal --- all attributes and methods are public and accessible (no example is provided)

2.2 Use naming rules to differentiate private members. In essence, this mode is similar to the Creation Mode of a large-size portal object, except that the names of some methods and attributes are underlined to show their private use.

// This. _ menber = member;

// _ Method = function () {}, but the external access is still accessible.

2.3 scope, nested functions, and closures

In JavaScript, only functions have scopes. The benefit of closures is that they can implement internal variables called outside the function. Returning an embedded function is the most common method to create a closure.

View code

 Function  Foo (){  VaR A = 10 ;  Function Bar () { * = 2 ;  Return  A ;}  Return  Bar ;}  VaR Baz = Foo (); Baz ();  //  Return 20 Baz (); //  Return 40 Baz (); //  Return 80  VaR Blat =Foo (); Blat ();  //  Return 20 because a new copy of A is being used 

The above Code actually involves the issue of shared variables. var Baz = Foo () declares a reference to the function bar. Share variable A when using Baz. For details, refer to the Javascript series (10): The javascript core (must be read by the advanced professional.

2.4 summarize the advantages and disadvantages of encapsulation:

Encapsulation protects the integrity of internal data. by limiting the access path of data to the valuers and value assignment devices, you can gain full control over values and values, this reduces the number of error check codes required by other functions. Image Reconstruction becomes easier. By disclosing only the methods specified in those interfaces, the coupling between modules can be weakened.

Encapsulation leads to a complex scope chain. It is difficult to learn, and it is easy for new users to get confused.

3 inheritance-inheritance in Javascript is very complex and more complex than any other object-oriented language...Next time I will summarize it. I feel like I will inherit it. I can write a blog post. If it's okay, continue tomorrow.

All of the above are personal original, please reprinted When attached original link: http://www.cnblogs.com/tonylp

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.