Xiao Bai talk about the understanding of JS prototype chain _javascript Skills

Source: Internet
Author: User
Tags define prototype inheritance

Prototype chain to understand a bit around, online data is also a lot, every night when I always like to find some prototype chain on the Internet and closure of the article look, the effect is excellent.

Don't dwell on the jargon, it's really not going to help you, except to twist your brain. Simply look at the prototype chain, think of something unrelated to the code, such as people, demons and Simon.

1 The person is a person of his mother is born, Demon is a demon his mother is born. The human and the demon are the object instance, but the human and the demon his mother is the archetype. A prototype is also an object, called a prototype object.

2 people his mother and his father can give birth to a bunch of people baby, demon his mother and the demon his dad snapped can give birth to a bunch of demon baby, PA is the constructor, commonly known as the creation of people.

3 The person's mother will record the snapped information, so it can be found through the person's mom snapped information, that is, through the prototype object to find the constructor.

4 The mother can have a lot of babies, but these babies have only one mother, this is the uniqueness of the prototype.

5 The people of his mother is also the mother of his mother, through the people to find a mother of his mother, and then through the people of his mother's mother to find the mother of his mom ..., this relationship is called the prototype chain.

6 The prototype chain is not infinite, when you through the people's mother has been looking up, and finally found that you will find the mother of his mother. The mother is not a human, that is, the prototype chain ultimately point to null.

7 people who are born to the mother will be someone's appearance, demon his mother born Demon will have demon ugly, this is called inheritance.

8 You inherit your mother's complexion, your mother has inherited your mother's fucking complexion, your mother's mother ..., this is the inheritance of the prototype chain.

9 You do not have a home, then your family refers to your mother's home, your mother does not have a home, then your family refers to your mother's mother's home ... This is the search for the prototype chain up.

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

11 Although you wash the hair dyed into yellow hair, but you can not change your mother's appearance, your mother's brother and sister and your hair is not a little bit of a haircut, that is, object instances can not change the properties of the prototype.

12) But your home is burned by you, that is to say your mother home your brother's family have been burnt, this is the prototype properties of the share.

13 Your mother nickname Jane, the neighbor's aunt called you precious son, but your mother hair from fluttering soft made a golden Lion queen, next door aunt all called you Golden Lion Prince, this is called the dynamic nature of the prototype.

14 Your mother beauty, and ran to the Korean plastic surgery, the whole to your mother's mother can not recognize, even if your mother's hair in return to float soft, but next door neighbor or call you Golden Lion Prince. Because no one recognized your mother, after the plastic surgery your mother has been recycled, this is the overall rewriting of the prototype.

Nima! It's enough for you! Don ' t bb! Show me The code!

function person (name) {this.name = name} function Mother () {} Mother.prototype = {//mother prototype age:18, home: [' Bei
Jing ', ' Shanghai ']}; Person.prototype = new Mother (); The person's prototype is mother//viewed with the Chrome Debug tool, providing a __proto__ interface to view the prototype var p1 = new Person (' Jack '); P1: ' Jack '; __proto__:18,[' Beijing ', ' Shanghai '] var p2 = new Person (' Mark '); P2: ' Mark '; 
__proto__:18,[' Beijing ', ' Shanghai '] p1.age = 20; /* Instance does not change the base value attribute of the prototype, as you do with your mother and your hair. * Adding an Age attribute to the P1 instance is a normal operation, regardless of the prototype. with Var o{};
O.age=20 the same.
* P1: There are a number of attributes of age, and __proto__, like Mother.prototype, age=18. 
* P2: Only attributes name,__proto__ like Mother.prototype * * p1.home[0] = ' Shenzhen ';
/* The reference to the share of the type attribute in the prototype, just as you burn your home, you burn your family home. * P1: ' Jack ', 20; __proto__:18,[' Shenzhen ', ' Shanghai '] * p2: ' Mark '; 
__proto__:18,[' Shenzhen ', ' Shanghai '] * * p1.home = [' Hangzhou ', ' Guangzhou ']; /* In fact, the same operation as P1.age=20. In exchange for this understanding: Var o{}; o.house=[' big ', ' house '] * P1: ' Jack ', 20,[' Hangzhou ', ' Guangzhou ']; __proto__:18,[' Shenzhen ', ' Shanghai '] * p2: ' Mark '; __proto__:18,[' Shenzhen ', ' Shanghai ']
*/delete p1.age; /* Delete the custom attribute, the original overridden value of the prototype will be out of the daylight. Here is the upward search mechanism, so there is the following dynamic * P1: ' Jack ', [' Hangzhou ', ' Guangzhou ']; __proto__:18,[' Shenzhen ', ' Shanghai '] * p2: ' Mark '; 
__proto__:18,[' Shenzhen ', ' Shanghai '] * * Person.prototype.lastName = ' Jin '; /* Rewrite the prototype and dynamically react to the instance. Just like your mom turned trendy, the neighbors mentioned you said it was the son of a boomer. Note, here we rewrite the person's prototype, which is to add a lastName attribute to mother, equivalent to Mother.lastname= ' Jin '
Here is not change mother.prototype, change different levels, the effect will often have very big 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 to say someone changed a mother. * Replace this understanding: Var a=10; B=a; a=20; C=a.
So B does not change, it becomes C, so the P3 is changed, it has nothing to do with mother. * 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 prototype prototype, dynamic response to the instance.
Just like your mother's a new fashion, neighbors mention you say your grandma really tide * Note, here we rewrite is mother.prototype,p1p2 will change, but above P3 with mother has no ties, does 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 the prototype prototype!
This time mother's prototype has completely become a new object!
* Because 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 = new person (' Luffy ') again; This time, if you need to apply these changes, it is necessary to reconnect the person's prototype to the mother//P5: ' Luffy '; __proto__: 2, [' Run ', ' walk '] p1.__proto__.__proto__.__
proto__.__proto__//null, you said the end of the prototype chain is not NULL?  mother.__proto__.__proto__.__proto__//null, you said the end of the prototype chain is not NULL?

Can you read the basics?

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

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

var obj = new Object ();
Obj.name= ' xxx '; 

Does that mean you understand it? The same thing.

So why p1.home[0] = ' Shenzhen ' does not create a home array attribute under P1, and then set its first to ' Shenzhen '? We still forget this first, think of the Obj object above, if written like this: var obj.name = ' xxx ', obj.num = [100, 200], can you get the result you want? Obviously, you can't get anything except the error. Since obj has not been 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 one step. If you want to create a home array under P1, of course this is the case:

P1.home = []; 

Isn't that the most common way we can do that?

The reason p1.home[0] = ' Shenzhen ' does not directly complain 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 previous prototype. All the way to the end of the prototype chain, that is, to null has not been found, return a undefined. When we enter p1.home[0], the same search mechanism, first search P1 to see if there is a property and method named Home, and then step up to find. Finally we found it in the prototype of Mother, so modifying him is equivalent to modifying the Mother prototype.

Sentence summary: p1.home[0] = ' Shenzhen ' equals to mother.prototype.home[0] = ' Shenzhen '.

As you can see from the above analysis, the main problem with prototype chain inheritance is the sharing of attributes, and many times we just want to share the methods rather than share the attributes, ideally each instance should have a separate attribute. As a result, there are two ways to improve the prototype inheritance:

1) Combination Inheritance

function Mother (age) {
this.age = age;
This.hobby = [' Running ', ' Football ']
}
Mother.prototype.showAge = function () {
console.log (this.age); 
};  
function person (name, age) { 
Mother.call (this, age); Second execution
this.name = name; 
}
Person.prototype = new Mother (); First execution
Person.prototype.constructor = person;
Person.prototype.showName = function () {
console.log (this.name);
}
var p1 = new Person (' Jack '); 
P1.hobby.push (' basketball '); P1: ' Jack '; __proto__:20,[' running ', ' football ']

The result is purple:

Here for the first time, get Person.prototype.age = undefined, Person.prototype.hobby = [' Running ', ' Football '], the second execution is var p1 = new per When son (' Jack ', 20), gets p1.age =20, p1.hobby = [' Running ', ' Football '],push, becomes p1.hobby = [' Running ', ' Football '], ' BASKETB All ']. In fact, to distinguish the change of this, it is relatively simple to understand, this simple replacement will be able to get this result. If you feel a bit more confused, try to throw away the concept inside your head, and then run your code from top to bottom in your browser.

With the second execution of the prototype's constructor Mother (), we copy the attributes of a prototype in the object instance so that the separation from the prototype attribute is independent. Careful you will find that the first time we call Mother (), as if nothing is used, can not call him? Can, there is the following parasitic modular inheritance.

2) Parasitic modular inheritance

function Object (o) {
function F () {}
f.prototype = O;
return new F ();
}
function Inheritprototype (person, Mother) {
var prototype = object (Mother.prototype); 
Prototype.constructor = person; 
Person.prototype = prototype; 
}
function Mother (age) {
this.age = age;
This.hobby = [' Running ', ' Football ']
}
Mother.prototype.showAge = function () {
console.log (this.age); 
};
function person (name, age) { 
Mother.call (this, age);
this.name = name;
Inheritprototype (person, Mother);
Person.prototype.showName = function () {
console.log (this.name);
}
var p1 = new Person (' Jack '); 
P1.hobby.push (' basketball ');//P1: ' Jack '; __proto__:20,[' running ', ' football ']

The result is purple:

There are no more age and hobby attributes in the prototype, there are only two methods, which are the results we want!

The key point is in Object (O), where a temporary object is borrowed to subtly avoid calling new Mother (), and then return the prototype as 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

-------------------------------------------------------------------------------

Said so much, in fact, there is only one core: attribute sharing and independent control, when your object instance requires a separate attribute, all the essence of the practice is to create attributes in the object instance. If you don't think about it too much, you can simply define the attributes you need independently in person to override the properties of the stereotype. In short, when using prototype inheritance, you should pay special attention to the attributes in the prototype, because they are all far-reaching.

Below a simple list of the various methods of creating objects in JS, now the most commonly used method is the combination mode, familiar students can skip to the end of the article to praise.

1) Original mode

1. Original mode, object literal way
var person = { 
name: ' Jack ',
age:18,
sayname:function () {alert (this.name);}
};
//1. Original mode, Object constructor method
var person = new Object ();
Person.name = ' Jack ';
Person.age =;
Person.sayname = function () {
alert (this.name);

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

2) Factory mode

2. Factory mode, define a function Create Object function
Creatperson (name, age) {
var temp = new Object (); 
Person.name = name;
Person.age = age;
Person.sayname = function () {
alert (this.name);
};
return temp; 
}

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

3) constructor

3. Constructor pattern, define a constructor function person
(name, age) {
this.name = name for the object;
This.age = age;
This.sayname = function () {
alert (this.name);}
;
} var p1 = new Person (' Jack ', 18); Create a P1 object

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

4) Prototype mode

4. Prototype mode, directly define prototype property
function person () {}
Person.prototype.name = ' Jack ';
Person.prototype.age =;
Person.prototype.sayName = function () {alert (this.name);};
4. Prototype mode, literal definition method
function person () {}
Person.prototype = {
name: ' Jack ',
age:18,
sayname: function () {alert (this.name);}
};
var p1 = new Person (); Name= ' Jack '

What you need to note here is the sharing of the prototype properties and methods, that is, all instances are simply referencing the attribute methods in the prototype, and any changes that occur in any one place can cause changes in other instances.

5) Blending Mode (construction + prototype)

5. Prototype construction combination mode,
function person (name, age) {
this.name = name;
This.age = age;
}
Person.prototype = {
hobby: [' Running ', ' Football '];
Sayname:function () {alert (this.name);},
sayage:function () {alert (this.age);}
;
var p1 = new Person (' Jack '); 
P1: ' Jack ', 20; __proto__: [' Running ', ' Football '],sayname,sayage
var p2 = new Person (' Mark ', 18); 

The practice is to put a separate property method into the constructor, while the part that can be shared is put into the prototype, which saves memory while preserving the independence of the object instance.

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.