Front-End Basics (ii): The understanding of JS's prototype chain

Source: Internet
Author: User

Before always the basic knowledge of the front end is not very detailed, the basic skills are not solid, but the fundamental knowledge of the front-end development is the foundation of future career development, although oneself always with a practice is the only criterion to test the truth, write code Practice project is the only, but often encountered know how to solve the problem, But do not know what a method to use, the principle of the method is what, now feel that the basic knowledge of the university learning is still very important, must have their own understanding to go farther.

Regardless of the future of their own learning new technology, but original aim, basic solid, high learning efficiency.

Nonsense so much, began the four parts of today's understanding.

First, JS of the prototype chain to understand the way

Second, the prototype understanding

III. rules

Iv. common methods of creating objects for JS

First, the original chain to understand the way

Each prototype chain is difficult to understand and often error-prone, or not explained in the first place.

1. What is an object instance and what is a prototype (object)?

2. What is a constructor function?

3. Find constructors by prototype objects

4, the uniqueness of the prototype

5. Prototype chain

6. The prototype chain eventually points to null

7. Inheritance

8, the inheritance of the prototype chain

9, the prototype chain up search

10. Properties of an object can be customized

11. Object instances cannot alter prototype properties

12. Sharing of prototype attributes

13, the dynamic nature of the prototype

14, the rewriting of the prototype

I go, this is too much, do not want to see, I have been blindfolded. And so on, learning itself is a painful process, but when you understand things through your own, this mechanism is easier to understand.

You can understand this:

1, "The person is the life, the demon is the demon born." "The human and the demon are the object instance, the human is the mother and the demon All is the prototype, also called the prototype object."

2, "Human birth and demon birth" are all constructs a function, from scratch the process

3. "One can find out who his father is by his mother", that is, the constructor is found through the prototype.

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

5, "Man fuck mom, and people fuck Mom, ...." "That's the prototype chain

6, the prototype chain is not infinitely long, through inheritance can be constantly looking up, the final prototype chain pointing to null

7, "people inherit the nature of the people, the demon inherited the demon-mother attribute." ”

8, "People have inherited people fucking skin color and so on, people fucking heirs fucking skin color and so on ... "This is prototype inheritance.

9, "You do not have a home, your family refers to your mother's house, your mother has no home, then your home is pointing to your mother's mother's home", this is the prototype chain of upward search.

10, "You will inherit your mother's appearance, but you can dye hair cut hair and so on", that is, the properties of the object can be customized.

11, "Although you change your hair color and so on, but you can not change your mother's appearance", this is the object instance can not change the properties of the prototype.

12, "Your home is playing with fire you said, that is to say your home, your mother's house, your brothers home, are less, this is the prototype sharing"

13, "Your mother nickname" Small Cui ", neighbors call You" little cui son ", but your mother did a handsome hairstyle, nicknamed changed to" Golden Lion King ", Neighbors Call You," Golden Lion Prince "", this is the dynamic nature of the prototype. "

14, "Your Mother beauty, plastic surgery, no one knows, and then the whole back", this is called the overall rewrite of the prototype.

Before we use code to illustrate the prototype chain, let's figure out what the function and functions are, what is the relationship between the constructor, the prototype, and the instance?

Answer: 1. All functions are instances of function.

2, on the constructor has a prototype attribute prototype, the property is also an object;

3, then there is a constructor property on the prototype object, which points to the constructor function;

4, and the instance object has a _proto_ property, which also points to the prototype object, and the property is not a standard property, and is not intended for use in programming, which is used within the browser.

functionPerson (name) { This. name=name}functionmother () {}mother.prototype={//mother prototype self-bringing property prototypeAge:20, home:[' Beijing ', ' Shanghai ']};p erson.prototype=NewMother ();//The person's prototype is mothervarp1=NewPerson (' Tom ');//p1: ' Tom '; _proto_:20,[' Beijing ', ' Shanghai ']varP2=NewPerson (' Mark ')//p2: ' Mark '; _proto_:20,[' Beijing ', ' Shanghai ']p1.age=24;//The instance cannot change the base property value of the prototype, and adds an age attribute under the P1 instance, regardless of the prototype//p1: ' Tom ', 24;_proto_:20,[' Beijing ', ' Shanghai ']p1.home[0]= ' Shenzhen '; //reference type Zodiac in the prototype share, as you burned your house, burned your family's home//p1: ' Tom ', 24;_proto_:20,[' Shenzhen ', ' Shanghai ']//p2: ' Mark '; _proto_:20,[' Shenzhen ', ' Shanghai ']P1.home=[' Hangzhou ', ' Guangzhou '];//in fact, the same as the p1.age=20 operation//p1: ' Tom ', 24,[' Hangzhou ', ' Guangzhou '];_proto_:20,[' Shenzhen ', ' Shanghai '//p2: ' Mark '; _proto_:20,[' Shenzhen ', ' Shanghai ']DeleteP1.age;//After you delete a custom property, the original overlay will be able to be found, which is the search mechanism//p1: ' Tom ', [' Hangzhou ', ' Guangzhou '];_proto_:20,[' Shenzhen ', ' Shanghai ']//p2: ' Mark '; _proto_:20,[' Shenzhen ', ' Shanghai ']Person.prototype.lastname= ' Cheng ';//rewrite the prototype, the dynamic response in the instance. We're rewriting the person's prototype, adding a last to the mother attribute//equivalent to mother.lastname= ' Cheng '//this is not mother. Prototype, change the different levels, the effect will be very big difference//p1: ' Tom ', [' Hangzhou ', ' Guangzhou '];_proto_: ' Cheng '; _proto_:20,[' Shenzhen ', ' Shanghai ']//p2: ' Mark ', [' Hangzhou ', ' Guangzhou '];_proto_: ' Cheng '; _proto_:20,[' Shenzhen ', ' Shanghai 'Person.prototype={age:28, Address:{country:' USA ', City: ' Washington '}};varp3=NewPerson (' Obama ');//rewrite the prototype, this time the person's prototype completely changed//p1: ' Tom ', [' Hangzhou ', ' Guangzhou '];_proto_: ' Cheng '; _proto_:20,[' Shenzhen ', ' Shanghai ']//p2: ' Mark ', [' Hangzhou ', ' Guangzhou '];_proto_: ' Cheng '; _proto_:20,[' Shenzhen ', ' Shanghai ']//P3: ' OBMA '; _proto_:28{country: ' USA ', City: ' Washington '}mother.prototype.no=20110408;//The prototype is rewritten, the dynamic response is in the instance,//P1 and P2 will change, but P3 won't change, P3 has nothing to do with mother.//p1: ' Tom ', [' Hangzhou ', ' Guangzhou '];_proto_: ' Cheng '; _proto_:20,[' Shenzhen ', ' Shanghai '],20110408//p2: ' Mark ', [' Hangzhou ', ' Guangzhou '];_proto_: ' Cheng '; _proto_:20,[' Shenzhen ', ' Shanghai '],20110408//P3: ' Obama '; _proto_:28{country: ' USA ', City: ' Washington '}Mother.prototype={car:2, hobby:[' Run ', ' walk ']};varp4=NewPerson (' Tony ');//rewrite the prototype, when the mother prototype has changed completely//the person above and the mother have been disconnected, and how the mother changed will not affect the person//P4: ' Tony '; _proto_:28{country: ' USA ', City: ' Washington '}Person.prototype=NewMother ();//Bind againvarp5=NewPerson (' luccy ');//this time, if you need to apply this change, you need to re-bind the person prototype to mother.//P5: ' Luccy '; _proto_:2,[' run ', ' walk ']p1.__proto__.__proto__.__proto__.__proto__//NULL, the original chain endpoint is nullmother.__proto__.__proto__.__proto__//NULL, the end of the prototype chain is null

Second, the prototype understanding

In JavaScript, the prototype is also an object , which can be used to implement the object's property inheritance,the JavaScript object contains a Protype internal property, this property The corresponding is the prototype of the object . The JavaScript prototype object also contains a constructor property that corresponds to the constructor that creates all instances of the prototype.

Note: Protype is not directly accessible as an intrinsic property of an object, but Google Chrome provides a _proto_ non-standard accessor.

III. rules

In JavaScript, each function has a prototype property, and when a function is used as a constructor to create an instance, the prototype property value is assigned to all object instances (that is, all instances set the "_proto_" attribute).

Object: Prototype Property

Prototype object: Protype property, construction property

Object instance: _proto_ Property

The new process is divided into three steps:

var p=new person (' Zhang San ', 20);

1, var p={}; Initialize an object P

2, P._proto_=person.prototype; Set the _proto_ property of the object p to Person.prototype

3, Person.call (' Zhang San ', 20); Call the constructor person to initialize p.

The main problem with the inheritance of the prototype chain is the sharing of attributes. Improved method of prototype inheritance:

(1) Combination inheritance

functionMother (age) { This. age=Age ;  This. hobby=[' running ', ' Football ']}mother.prototype.showage=function() {Console.log ( This. age);}functionPerson (Name,age) {Mother.call ( This, age);//Second Execution     This. name=name;} Person.prototype=NewMother ();//First time executionPerson.protype.constructor=Person;person.prototype.showname=function() {Console.log ( This. name);}varp1=NewPerson (' Jack ', 20);p 1.hobby.push (' Basketball ');//p1: ' Jack '; _proto_:20,[' running ', ' Football ']varP2=NewPerson (' mark ', 18);//p2: ' Mark '; _proto_:18,[' running ', ' Football ']

Execution Result:

Iv. common methods of creating objects for JS

(1) Original mode

// 1, the original mode. Object literal way var person={name:' Jack ', Age:sayname:function() { Alert (this. name);}; // 1. Primitive mode, object constructor mode var person=New  object ();p erson.name= ' Jack ';p erson.age=18; Person.sayname=function() {alert (this. name);};

The number of code reuse is large, so the Factory mode is generated.

(2) Factory mode

// 2, Factory mode, define a function to create an object function Createperson (name,age) {var temp=New  Object ();p erson.name=name;person.age =Age;person.sayname=function() {alert (this. name);}; return temp;}

Factory mode is batch production, efficiency

(3) Constructors

// 3. Constructor mode, one constructor for object top function Person (name,age) {this. name=name; this. age= age; this. sayname=function() {alert (this. name);};} var p1=New person (' Jack ',);   // Create a P1 object person (' Jack ',);    // attribute methods to the Window object, window.name= ' Jack '

Constructors are similar to C + +, Java constructors, and are easy to understand.

(4) Prototype mode

//4. Prototype mode, directly define ProttypefunctionPerson () {person.prototype.name= ' Jack ';p erson.prototype.age=18;p Erson.prototype.sayName=function() {Alert ( This. name);}}//4, prototype mode, the way of literal definitionfunctionPerson () {Person.prototype={name:' Jack ', Age:18, Sayname:function() {Alert ( This. name);};varp1=NewPerson ();//name= ' Jack 'varP2=NewPerson ();//name= ' Jack '}

It is important to note that the prototype properties and methods are shared, that is, all instances are simply referencing the attribute methods in the prototype, and any change in the local poor will cause changes in other instances.

Front-End Basics (ii): JS's understanding of the prototype chain

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.