Javascript design pattern communication (2) -- prototype Pattern

Source: Internet
Author: User
Prototype pattern is a creation mode. In the gof book, its intention is described as specifying the object type with the prototype instance, and creating new objects by copying these prototypes.

Prototype pattern itself is actually very simple. Any object that provides the clone () method can become a prototype object. All objects copied through it belong to a class of object. In static languages, this mode is used to specify the object type during runtime. Compared with the factory mode, this mode does not need to create a factory class structure that is parallel to the class hierarchy, which is much easier to implement.

Clone three JS implementations

In JS, the implementation of the clone method is not difficult. For the six basic types of JS, the string Boolean undefined null number can be directly assigned with the = value. The only trouble is that the object.
For an object, we can use the clone function to copy all its members as a method. This function can be defined as follows:

[Copy]

Code:


        function clone()
        {
                var ret=new Object();
                for(var p in this)
                {
                        ret[p]=this[p];
                }
        } 

But we obviously face a problem: this [p] may also be an object, so we may need to implement deepclone using recursion.

[Copy]

Code:


        function deepClone()
        {
                var ret=new Object();
                for(var p in this)
                {
                        ret[p]=deepClone.call(this[p]);
                }
        } 

For JS, there is another way to implement clone. In JavaScript, the prototype attribute of the constructor specifies a type of prototype. when instantiating, this prototype is used as the prototype of the object. In particular, this prototype object may also be constructed from a prototype, which forms a structure similar to inheritance, therefore, the prototype-oriented features of JavaScript are also called prototype inheritance (although I do not agree with this practice, I 'd like to mention it ).

Back to our previous prototype pattern, JavaScript's inherent reference prototype inheritance provides us with another clone implementation method:

[Copy]

Code:


        function prototypeClone()
        {
                var tmp=function(){};
                tmp.prototype=this;
                return new tmp;
        } 

In this way, the cloned object shares the attributes of a prototype in read-only mode, and its biggest advantage is that the speed is very fast. This method can be used when we want to quickly copy large objects, however, it will reduce the access speed and reflect changes to the parent node in real time.

Built-in object clone

However, we have not considered the built-in objects so far, and the built-in objects cannot be cloned using the common method. We need to consider the following built-in objects:
Function Array string Boolean number date
Regexp error and math do not need to be cloned.

For a function, it is impossible to generate a copy completely, because we cannot guarantee that the constructed function is in the same scope as the original function, but it is easy to implement the function without the scope:
Eval (this );
Or use function to construct
Return function (new string ("return") + This )();

Function itself is an object. Therefore, you must add the object clone function to implement functionprototypeclone.

[Copy]

Code:


        function functionClone()
        {
                var ret=Function(new String("return ")+this)();
                for(var p in this)
                {
                        ret[p]=this[p];
                }
        }
        function functionDeepClone()
        {
                var ret=Function(new String("return ")+this)()
                for(var p in this)
                {
                        ret[p]=deepClone.call(this[p]);
                }
        }
        function functionPrototypeClone()
        {                
                var tmp=Function.prototype;
                Function.prototype=this;
                var ret=(new Function(new String("return ")+this))();
                Function.prototype=tmp;
                return ret;
        } 

Array only needs to ensure that the length is correct.

[Copy]

Code:


        function arrayClone()
        {
                var ret=new Array();
                for(var p in this)
                {
                        ret[p]=this[p];
                }
        }
        function arrayDeepClone()
        {
                var ret=new Array();
                for(var p in this)
                {
                        ret[p]=deepClone.call(this[p]);
                }
        }
        function arrayPrototypeClone()
        {                
                var tmp=Array.prototype;
                Array.prototype=this;
                var ret=new Array();
                Array.prototype=tmp;
                return ret;
        } 

The date object provides gettime, so it can be easily implemented.

[Copy]

Code:


        function arrayClone()
        {
                var ret=new Date();
                ret.setTime(this.getTime());
                for(var p in this)
                {
                        ret[p]=this[p];
                }
        }
        function arrayDeepClone()
        {
                var ret=new Date();
                ret.setTime(this.getTime());

                for(var p in this)
                {
                        ret[p]=deepClone.call(this[p]);
                }
        }
        function arrayPrototypeClone()
        {                
                var tmp=Date.prototype;
                Date.prototype=this;
                var ret=new Date();
                ret.setTime(this.getTime());
                Date.prototype=tmp;
                return ret;
        } 

String Boolean number is a read-only object, so you only need to =.

We have discussed three clone implementation methods, each of which has an appropriate semantic environment, for example, for an array, if it is understood as a collection, the shortest clone should be used (if set a is a subset of B, A should be guaranteed. clone () is also a subset of B). If we understand it as a vector, we should use deep clone (ensure that the component operation on vector A should not affect vector. clone () component ). One of the most common application scenarios of prototypeclone is the deep priority search algorithm. To expand the solution space tree, we usually need to quickly construct a copy. If clone or deepclone is used, this will be very slow, the deep priority search feature is that the parent node does not change before the byte point is destroyed, so prototypeclone is very suitable.

Appendix: Prototype-Oriented Programming and prototype Pattern
The prototype-oriented language idea is exactly the same as the prototype mode: The objects cloned from the same prototype are a class of objects. The prototype-oriented language provides language-level support for this mode, that is, all the definitions of "classes" are implemented by specifying a prototype of the class (class-based programming describes a class object through class structure Declaration, meta-class describes a class object by constructing a class object ). The prototype is cloned once for each instance. However, this method causes information redundancy: all objects hold a clone copy of the prototype object, and once an object is constructed, modifying a prototype does not have any impact on it, which is inconvenient for people who wish to uniformly change a certain type of objects in the program. As a result, a work ing method produces a reference-type prototype object, which is called a copy-type prototype object. The reference prototype object does not clone the prototype, but saves a pointer to the prototype. when accessing the property, first check its own property. When it finds that the property does not exist, then, the pointer is used to obtain the corresponding property from the prototype. The reference prototype is the implementation of JavaScript prototype-oriented features.

PS. I have consulted the original authors of this series.
 

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.