Simple and rude understanding of JS prototype chain--JS Object-oriented programming

Source: Internet
Author: User

Prototype chain to understand a bit around, the online material is also a lot, every night when sleep is always like to find some prototype chain online and closure of the article look, the effect is very good.

Don't get tangled up in that pile of jargon, that's not really going to help you unless you twist your brains. Simply look at the prototype chain and try something unrelated to the code, such as people, demons, and shemale.

1) Man is a man who is born of a mother, a demon is born of a demon. Both the man and the demon are the object instances, and the man's mother and Demon are the prototypes. Prototypes are also objects, called prototype objects.

2) People his mother and the people his father snapped can give birth to a bunch of baby, demon his mother and demon his father can give birth to a bunch of demon Baby, PA PA is the structure function, commonly known as building people.

3) The person will be able to record the information, so you can get the information through the person's mother, that is, the prototype object can find the constructor function.

4) People can give birth to a lot of babies, but these babies have only one mother, which is the uniqueness of the prototype.

5) The person who is the mother is also the mother of the mother born, through the people his mother to find the mother of the hell, and then through the human mother to find the mother damn ..., this relationship is called the prototype chain.

6) The prototype chain is not infinite, when you go through the human mother to look up, and finally found that you will find the mother of the damn ... The mother is not a human, that is, the prototype chain eventually points to null.

7) The person who the mother born person will be someone's appearance, demon his mother born Demon will have demon ugly, this is called Inherit.

8) You have inherited your mother's skin color, your mother has inherited your mother's fucking complexion, your mother fucking ..., this is the inheritance of the prototype chain.

9) You talk about the object, her mother let you take the property card to pick up, if you do not, then her mother will ask your mother whether, your mother did not that her mother will ask your mother her mother has not ... This is the upward search of the prototype chain.

10) You will inherit your mother's appearance, but you can also dye the hair to wash and cut, that is, the properties of the object can be customized, overwriting inherited properties.

11) Although you have washed and dyed yellow hair, but you can not change your mother's appearance, your mother's brother and sister with your yellow hair wash cut no matter, that the object instance cannot change the properties of the prototype.

12) But your family was burned by you, that is to say your home your mother's family are burned, this is the prototype attribute sharing.

13) Your mother's nickname Jane, the neighbor Niang all call you Jane son, but your mother hair from fluttering soft made of Golden Lion Queen, next door aunt all changed to call you chartered, this is called the dynamic nature of the prototype.

14) Your Mother beauty, and ran to South Korea plastic surgery, the whole to your mother can not recognize the mother, even if your mother's hair change back, but next door neighbor still call you Golden Lion Prince. Because no one recognized your mother, the plastic after your mother has melted down re-established, this is the overall rewrite of the prototype.

Nima! That's enough for you too! Don ' t bb! Show me the code!

function person (name) {this.name = name;} function mother () {}mother.prototype = {//mother's prototype age:18, home: [' Beijing ', ' Shanghai ']}; Person.prototype = new mother (); The person's prototype is mother//with Chrome Debugging tools, provides a __proto__ interface to view prototypes, there are two layers of prototypes, and you can just look at chrome a little better. var p1 = new Person (' Jack '); P1: ' Jack '; __proto__:{__proto__:18,[' Beijing ', ' shanghai ']}var p2 = new Person (' Mark '); P2: ' Mark ';  __proto__:{__proto__:18,[' Beijing ', ' shanghai ']}p1.age = 20; /* Instances cannot change the base value properties of the prototype, as you do with your mother's hair and hair. * Adding an Age property to the P1 instance is a normal operation, regardless of the prototype. with Var o={}; Like o.age=20. * P1: The following is an attribute of age, and __proto__, like Mother.prototype, age=18. * P2: Only attributes name,__proto__ as Mother.prototype */p1.home[0] = ' Shenzhen '; /* Share of the reference type attribute in the prototype, just as you burned your home and burned your family's home. * This is the first, the following carefully nagging about it? * P1: ' Jack ', 20;    __proto__:{__proto__:18,[' Shenzhen ', ' Shanghai ']} * p2: ' Mark '; __proto__:{__proto__:18,[' Shenzhen ', ' Shanghai ']} */p1.home = [' Hangzhou ', ' Guangzhou ']; /* In fact, the same operation as P1.age=20. Change to this understanding: Var o={}; o.home=[' big ', ' house '] * P1: ' Jack ', 20,[' Hangzhou ', ' Guangzhou ']; __proto__:{__proto__:18,[' Shenzhen ', ' Shanghai ']} * p2: ' Mark ';    __proto__:{__proto__:18,[' Shenzhen ', ' Shanghai ']} */delete p1.age; /* Once the properties of the instance are deleted, the original overridden values will be seen. As you shave your bald head, the charming little hair of heredity grows out.
* This is the upward search mechanism, first search you, then your mother, then your mother's mother, so your mother's changes will affect you dynamically. * P1: ' Jack ', [' Hangzhou ', ' Guangzhou ']; __proto__:{__proto__:18,[' Shenzhen ', ' Shanghai ']} * p2: ' Mark '; __proto__:{__proto__:18,[' Shenzhen ', ' Shanghai ']} */person.prototype.lastname = ' Jin '; /* Rewrite the prototype and react dynamically to the instance. Just as your mother is trendy, the neighbors mention you say your mother is really a tide. * Note, here we rewrite the person's prototype, is to add a lastName attribute to mother, equivalent to mother.lastname= ' Jin ' * Here is not to change mother.prototype, change the different levels, the effect will often have a great difference. * P1: ' Jack ', [' Hangzhou ', ' Guangzhou ']; __proto__:{' Jin ', __proto__:18,[' Shenzhen ', ' Shanghai ']} * p2: ' Mark '; __proto__:{' Jin ', __proto__:18,[' Shenzhen ', ' Shanghai ']} */person.prototype = {age:28, address: {country: ' USA ', City: ' Washington '}};var p3 = new Person (' Obama '); /* Rewrite the prototype! This time the person's prototype has completely become a new object, that is, man changed a mother, called stepmother. * Change to this understanding: Var a=10; B=a; a=20; C=a. So B does not change, become C, so P3 with stepmother change, and the mother has nothing to do. * P1: ' Jack ', [' Hangzhou ', ' Guangzhou ']; __proto__:{' Jin ', __proto__:18,[' Shenzhen ', ' Shanghai ']} * p2: ' Mark '; __proto__:{' Jin ', __proto__:18,[' SheNzhen ', ' Shanghai ']} * P3: ' Obama '; __proto__: {country: ' USA ', City: ' Washington '} */mother.prototype.no = 9527;/* rewrite the prototype Prototypes, which are dynamically reflected into the instance. Just like your mom's a damn fad, the neighbors mention you say your grandmother is a real wave. * Note, here we rewrite is mother.prototype,p1p2 will change, but the above P3 with the mother has no involvement, do not affect him. * P1: ' Jack ', [' Hangzhou ', ' Guangzhou ']; __proto__:{' Jin ', __proto__:18,[' Shenzhen ', ' Shanghai '],9527} * p2: ' Mark '; __proto__:{' Jin ', __proto__:18,[' Shenzhen ', ' Shanghai '],9527} * P3: ' Obama '; __proto__: + Country: ' USA ', City: ' Washington '} */mother.prototype = {car:2, hobby: [' run ', ' walk ']};var P4 = new Person (' Tony '); */* rewrite prototype prototypes! This time mother's prototype has completely become a new object! Man, he's got a damn stepmother! * As the above person and mother have been disconnected, this time mother how to change has not affected person. * P4: ' Tony '; __proto__: {country: ' USA ', City: ' Washington '} */person.prototype = new mother (); Bind var P5 again = new person (' Luffy ');//This time if you need to apply these changes, it is necessary to re-bind the person's prototype to the mother//P5: ' Luffy '; __proto__:{__proto__: 2 , [' Run ', ' Walk ']}p1.__proto__.__proto__.__proto__.__proto__//null, you say the end of the prototype chain is not NULL? Mother.__proto__.__proto__.__protO__//null, you say the end of the prototype chain is not NULL?

Have you read the basics?

Now say P1.age = 20, p1.home = [' Hangzhou ', ' Guangzhou '] and p1.home[0] = ' Shenzhen ' difference.  P1.home[0] = ' Shenzhen '; A summary of this is the form of p1.object.method,p1.object.property.

P1.age = 20; P1.home = [' Hangzhou ', ' Guangzhou ']; These two sentences are better understood, forget the prototypes first, and think about how we add properties to an ordinary object:

var obj = new Object (); obj.name= ' xxx '; Obj.num = [100, 200];    

Does that make sense? The same thing.

Then why p1.home[0] = ' Shenzhen ' will not create a home array property under P1 and then set its first to ' Shenzhen '? Let's just forget this, think of the Obj object above, if it's written like this: var obj.name = ' xxx ', obj.num = [100, 200], can you get the result you want? Obviously, you can't get anything but an error. Because obj is not yet defined, how can you add something to it? Similarly, the home in p1.home[0] is not defined under P1, so it is not possible to define home[0 directly in a single step. If you want to create a home array under P1, of course this is the case:

P1.home = []; P1.home[0] = ' Shenzhen ';

Isn't that the way we use it the most?

And the reason p1.home[0] = ' Shenzhen ' does not directly error, because there is a search mechanism in the prototype chain. When we enter the P1.object, the search mechanism of the prototype chain is to search for the corresponding value in the instance first, find it in the prototype, and then search for the top-level prototype. All the way to the end of the prototype chain is to return a undefined if the null has not been found. When we enter P1.home[0], is also the same search mechanism, first search P1 see there is a property called home and methods, and then step up to find. Finally we found it in the prototype of mother, so modifying him would be equivalent to modifying the mother prototype.

In a nutshell: p1.home[0] = ' Shenzhen ' equals mother.prototype.home[0] = ' Shenzhen '.

As can be known from the above analysis, the main problem of the prototype chain inheritance is the sharing of attributes, many times we just want to share the method and do not want to share the property, ideally each instance should have a separate attribute. as a result, there are two ways to improve the prototype inheritance:

1) Combination InheritanceView Code

The result is Jiangzi:

The first time this is performed, get Person.prototype.age = undefined, Person.prototype.hobby = [' Running ', ' Football '], the second execution is var p1 = new Per Son (' Jack ', 20), got P1.age =20, p1.hobby = [' Running ', ' Football '],push after it became p1.hobby = [' Running ', ' Football ', ' Basketb All ']. In fact, it is easier to understand this change, and this can be achieved by simply replacing it. If the feeling is more around, try to throw away the concept inside the mind, and put yourself in the browser from top to bottom to execute the code, the result is not out?

By the second execution of the prototype's constructor, mother (), we copy the properties of a prototype in the object instance so that it is separate from the prototype attribute. Careful you will find that the first time we call Mother (), as if nothing to do, can not call him? Yes, we have the following parasitic combined inheritance.

2) Parasitic combined inheritanceView Code

The result is Jiangzi:

There are no more age and hobby attributes in the prototype, only two methods, which is exactly what we want!

The key is in Object (O), where a temporary object is borrowed to subtly avoid calling new mother (), and then returning the prototype to an O object instance, thus completing the prototype chain setup. Very round, right, that is because we can not directly set Person.prototype = Mother.prototype AH.

Summary

Having said so much, there is only one core: attribute sharing and independent control, when your object instances require independent attributes, all of which are created in object instances . If you don't think too much, you can directly define the attributes you need to be independent in person to overwrite the properties of the prototype. In summary, when using the prototype inheritance, you should pay special attention to the properties in the prototype, because they are reaching.

Below a simple list of the next JS in the creation of the object of the various methods, now the most common method is the combination mode, the familiar classmate can skip to the end of the article likes.

1) Original modeView Code

Obviously, when we want to create lots of person1, person2 ... , every time to knock a lot of code, Senior Copypaster are unbearable! Then there is the factory model of mass production.

2) Factory modeView Code

Factory mode is batch production, simple call can enter the creation of human mode (PA pa ... )。 Specify the name age can build a bunch of babies, free hands. But because it is factory-rigged, so you can not identify the object exactly what type, is a person or a dog silly (instanceof test for object), in addition to each time you create a separate temp object, code bloated, ya minute fly butterfly ah.

3) constructor functionView Code

Constructors are similar to the constructors of classes in C + +, Java, and are easy to understand, and the person can be identified as type (instanceof test for person, Object). But all instances are still independent, and the methods of the different instances are actually different functions. Here to forget the function two words, the sayname as an object to understand, that is to say Zhang San Sayname and John Doe Sayname is different existence, but obviously we expect to share a sayname to save memory.

4) Prototype modeView Code

It is important to note that there is a sharing of prototype properties and methods, that is, all instances only refer to the attribute methods in the prototype, and any changes that occur in any one place can cause changes to other instances.

5) Mixed Mode (construction + prototype)View Code

The practice is to put a separate attribute method into the constructor, while the part that can be shared is put into the prototype, which minimizes memory and preserves the independence of the object instance

Simple and rude understanding of JS prototype chain--JS Object-oriented programming

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.