Understanding the prototype pattern in JavaScript

Source: Internet
Author: User

First, why use prototype mode.

disadvantages of early adoption of a factory or constructor pattern:

1. Factory mode: function Creatperson Constructs a person object that contains all the necessary information according to the accepted parameters, this function can be called countless times, although the factory pattern solves the problem of creating multiple similar objects, There is no problem with object recognition (a custom object o is returned, and the type of the object o is not explicitly defined).

2. Constructor mode: The constructor calls the same as other OO languages, using the new operator to construct an instance of the person , the constructor in JavaScript is also a function (so you can directly invoke the method name directly like a normal function) just to create the object, which is not the same as other Oo languages (other OO language constructors are not functions, you cannot call the method name directly, The object must be created with the new operator, and the same point is that the first letter of the constructor is capitalized, and the first letter of the non-constructor is lowercase.

The constructor pattern solves the problem of creating multiple similar objects and object recognition, but the disadvantage is that using this pattern creates multiple function instances that accomplish the same task.

take the example above to analyze the memory:

At this point the Person1.isname===person2.isname is False

Functions with the same name on different instances are unequal, and we want to have a way to solve the problem of creating multiple similar objects and object recognition, and to have each instance share the same method.

The above example can be improved by referring the method to the outside of the constructor, which is written as a global function, This.isname points to a pointer:

Different instances are shared methods, but if there are a number of methods, there are a few we have to define a few global functions, so that our custom reference types are lost encapsulation, in order to solve this series of problems, so there is a prototype mode.

Second, understand the prototype model.

1. Understanding prototype patterns first understand prototype objects:

Each function we create (a function in JavaScript is also an object) has a prototype attribute (prototype), which is essentially a pointer to an object, The purpose of this object is to include properties and methods that can be shared by all instances of a particular type (in layman's words, all instances of this particular type can share the properties and methods contained in the prototype object).

2. Two ways to assign a prototype object:

The first type:

At this point the properties and methods of the instance object Person1 and Person2 are shared with the prototype object, so the result of the above example output is:

(You can see that Person1 and Person2 share a Sayname method, and their methods are the same)

The second type:

As with creating a reference object, you can also assign values to the prototype object in the form of a literal. The end result is the same as the result above, but one exception is that the constructor property no longer points to person, because the literal way of rewriting the prototype object, at this point the Contructor point to the object objects (here do not understand the memory analysis behind the principle of understanding).

But we can indicate that constructor points to person:

3. Memory analysis of prototype objects:

Referred to the memory analysis diagram in the third edition of the Advanced JavaScript program.

the relationship between the person constructor, the person prototype object, and the existing two instances of the person:

Each function tree has a prototype attribute (prototype), which is a pointer to the prototype object; By default, the prototype object contains a constructor (constructor) property (the prototype initially contains only constructor properties). This property contains a pointer to the prototype property, and with the figure above as an example, Person.prototype.constructor points to person, which allows you to continue adding additional properties and methods to the prototype object.

When the constructor is called to create a new instance, the instance contains an internal property (pointer) that points to the prototype object of the constructor, which exists between the instance and the constructor's prototype object, rather than between the instance and the constructor, that is, the intrinsic property is not directly related to the constructor function.

4. The values in the prototype object cannot be overridden by an object instance:

Example:

Test results:

You can see that the name in the prototype object has not been changed, person1.name from the instance, and Person2.name from the prototype.

In prototype mode, when the property value is read through Person1.name, the instance is first searched for an attribute with name, and some will not be looked up on the prototype object, and if not, then the prototype will go to search.

That is, when we add a property to the instance, this property prevents us from accessing the same name property on the prototype, but does not modify that property.

Memory analysis, the diagram omits the relationship to the person constructor:

The delete operator allows you to directly delete a property in an instance: Delete Person1.name.

5. The dynamic nature of the prototype:

The 4th said that the values in the prototype object cannot be modified (overridden) by an object instance, not that the values in the prototype object cannot be modified, and can still be modified as follows:

The test results are as follows:

because the process of looking up values in a prototype is a search, any modifications made to the prototype object are immediately reflected on the instance, even if the prototype was modified before the instance was created.

Instance:

Test results:

Memory Analysis:

(Friend changed to person5,function omitted content)

However, if you modify the prototype after you have created the instance, and you override the prototype object by literal assignment, this will cut off the connection between the existing prototype and any previously existing object instances (it is still possible to rewrite the prototype object in this way, rather than modifying the prototype after the instance was first created).

Instance:

Test results:

Memory Analysis:

(The figure refers to "JavaScript Advanced Programming 3rd Edition", the figure is not changed, the same principle)

6. The model of the native object:

All native reference types (Object, Array, String, and so on) define methods on the prototype of their constructors. For example: Array.prototype.sort (), String.prototype.substring and so on, the model of the native object can not only read all the default method references, but also can modify the prototype of the native object like the prototype of the custom object, so it can also add methods to the native object, but in practice we do not modify the model of the native object ( Naming conflicts, overriding native methods, and so on are all things we don't want to encounter in real-world development.

7. Several operations on prototype objects:

1) isprototypeof detects if the instance object contains a pointer to a prototype object, containing the return true, or false.

2) Object.getprototypeof (instance object), returns the prototype of this object, and the result is true.

Object.getprototypeof (person1). Name this way you can access the name value in the prototype object.

3) hasOwnProperty (inherited from Object) detects if a property exists in the instance, returns True, otherwise false.

The property value can be detected with in, except that it will return true regardless of whether the property is in the instance or in the prototype. About the detection properties I have another article: JavaScript data detection

4) Object.keys (prototype object) returns an array of strings containing all the enumerable properties:

Test results:

8. Disadvantages of Prototype objects:

The advantage of a prototype object is that all of the properties and methods in the prototype can be shared by many instances, and the disadvantage is that when the prototype contains a property of the value of the reference type, an instance object modifies the property of the reference type, which can also be reflected in other instance objects.

9. Good Practice:

1) Combine the constructor pattern with the prototype mode:

2) Dynamic Prototyping mode:

In addition to the above two modes there is a parasitic constructor mode and a safe constructor mode here is not summed up, no use to have no experience, above just I read the "JavaScript Advanced Program Third Edition" of the study notes, with their own understanding of the way summed up a bit.

Understanding the prototype pattern in JavaScript

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.