The ultimate explanation of JS prototype and prototype chain

Source: Internet
Author: User
Tags tidy

    function person () {        this. Name = ' John ';    }      var New Person ();     function () {        Console.log (this. Name);    };    Person.say (); // Hello,john

The code is very simple, and the person prototype object defines a common say method, although this occurs after the instance is constructed, but since the prototype method has been declared before the call, each subsequent instance will have the method. From this simple example, we can conclude that:

The purpose of a prototype object is to store shared methods and properties for each instance object, which is just a normal object. And all instances are shared with the same prototype object, so unlike instance methods or properties, the prototype object has only one copy.

Therefore, the following equation is established:

New Person (). Say
Maybe we'll write that too .
  function   person () { this . Name = ' John ' ;  var  person = new   person (); Person.prototype  = {say:  function () {Console.log ( ' Hello, ' + 

Unfortunately, the Person.say method was not found, so the error. In fact, the original intention is good: because if you want to add more properties and methods on the prototype object, we have to write a line person.prototype each time, rather than refining into an object directly. But this is a clever example of how to construct an instance object operation before adding a prototype method, which creates a problem:
When var person = new Person () , Person.prototype is: Person{} (of course, there is also the constructor property inside), That is, Person.prototype points to an empty object {}. For instance person, there is a prototype chain pointer Protoinside it, which points to the object that Person.prototype points to, which is {}. The person's prototype object is then reset to point to another object,

function}

Then person. The point of Proto is still unchanged, it points to the {} object inside there is no say method, because this error.

From this phenomenon we can draw:

In JS, the object in the invocation of a method will first look for the method in itself, if not, then go to the prototype chain to find, in turn, layer by step, where the prototype chain is the Proto property of the instance object.

The simplest and most effective way to make the above example run successfully is to exchange the order of the constructed objects and reset the prototype objects, namely:

function Person () {        this. Name = ' John ';    }      = {        function() {            Console.log (this. Name);        }    };     var New Person ();    Person.say (); // Hello John

a picture gives you a second understanding of the prototype chain

In fact, you just need to understand the structure of the prototype object:

Function.prototype = {        constructor:function,        __proto__: Parent prototype,        some prototype properties: ...    };

The prototype object of the function constructor to the function itself by default, the prototype object has a prototype attribute, in order to implement inheritance, there is also a prototype chain pointer Proto, which points to the previous layer of the prototype object, and the structure of the previous layer of the prototype object is still similar, so that the use of Proto always points to the prototype object of object, while the object's prototype objects are used with object. Proto = null represents the top of the prototype chain, thus changing the prototype chain inheritance of JavaScript and explaining why all JavaScript objects have the basic method of object.

Excerpt from: http://blog.csdn.net/kkkkkxiaofei/article/details/46474303#t0

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

I. Common objects and Function objects

In JavaScript, everything is Object! But the object is also different. is divided into ordinary objects and Function objects , Object, function is JS comes with the functions of the object . The following examples illustrate

 functionF1 () {};varF2 =function(){}; varF3 =NewFunction (' str ', ' Console.log (str) '); varO3 =NewF1 ();varO1 = {}; varO2 =NewObject (); Console.log (typeofObject);//functionConsole.log (typeofFunction);//functionConsole.log (typeofO1);//ObjectConsole.log (typeofO2);//ObjectConsole.log (typeofO3);//ObjectConsole.log (typeofF1);//functionConsole.log (typeofF2);//functionConsole.log (typeofF3);//function

In the above example O1 O2 O3 is a normal object, F1 F2 F3 is a function object. How to differentiate, in fact, is very simple, all the objects created by the new function () are function objects, others are ordinary objects . F1,f2, in the final analysis, is created by means of new Function (). Function Object is also created through the New function ().

Two. Prototype objects
In JavaScript, each time an object (function) is defined, the object contains some predefined properties. One of the properties of the function object is the prototype object prototype. Note: normal objects do not have prototype, but have __proto__ properties.

The prototype object is actually an ordinary object (except for Function.prototype, which is a function object, but it is very special, he has no prototype attribute (previously said the function object has prototype property)). Look at the following example:

  function   // f1{}  Console.log (//  object  console.log (typeof  Function.prototype) //  Function, this special  Console.log (typeof  object.prototype) //   Object  Console.log (typeof  Function.prototype.prototype) // undefined 

The output from this console.log (F1.prototype)//f1 {} shows thatF1.prototype is an instance object of F1 . When F1 is created, it creates an instance object of it and assigns it the prototype, the basic process is as follows:

var New  = temp;

Therefore, function.prototype why the function object is solved, the above mentioned that all the new function () produced by the object is a function object, so Temp1 is a function object.

var New  = Temp1;

What is the prototype object for? The primary function is for inheritance. Give examples:

  var function (name) {   this. Name = name  };    function () {     returnthis. Name;   }   var New Person (' Zhangjiahao ');   // Zhangjiahao

As can be seen from this example, by setting a property of a function object to Person.prototype, the normal object with the person instance (in the example: ZJH) Inherits this property. specifically how to achieve the inheritance, it is necessary to talk about the following prototype chain.

Three Prototype chain
JS has a built-in property called __proto__ when creating an object (whether it is a normal object or a function object), and is used to point to the prototype object prototype of the function object that created it. Take the example above:

// true

Similarly, the Person.prototype object has the __proto__ property, which points to the prototype of the Function object (object) that created it.

// true

Continue, the Object.prototype object also has the __proto__ property, but it is more special, NULL

// NULL

We put this chain of __proto__ up until the object.prototype.__proto__ null is called the prototype chain . Such as:

Four Memory structure diagram
For a more in-depth and intuitive understanding, let's draw a diagram of the above memory structure:

Paint Conventions:

Explanation of Doubt:
1.object.__proto__ = = = Function.prototype//True
Object is a function object, created by the new function (), so object.__proto__ points to function.prototype.

2.function.__proto__ = = = Function.prototype//True
function is also an object and is created by the new function (), so function.__proto__ points to function.prototype.

Oneself is created by oneself, seem not logical, but think carefully, the real world also have some similar, how you come, your mother is born, your mother how come, your grandmother is born, ... The apes evolved, where the apes came from, all the way back ... that's none, (Null for everything)
As the "moral Sutra" says, "No, the beginning of the world of the name."

3.function.prototype.__proto__ = = = Object.prototype//true
In fact, I'm a little confused, but I can also try to explain.
Function.prototype is a function object, theoretically his __proto__ should point to Function.prototype, is himself, he points to himself, no meaning.
JS has always emphasized that everything is object, function object is also object, give him to recognize an ancestor, point to Object.prototype. object.prototype.__proto__ = = = NULL to ensure that the prototype chain ends normally.

Five Constructor
The prototype object prototype has a predefined constructor property that references its function object . This is a circular reference
Person.prototype.constructor = = = Person//true
Function.prototype.constructor = = = Function//true
Object.prototype.constructor = = = Object//true

Complete the above memory structure diagram:

There are two points to note:
(1) Note that the object.constructor===function;//true itself is a function-constructed object.
(2) How to find the constructor of an object is to look for the object to which the first constructor property is pointing on the prototype chain of the object

Six Summarize
1. Prototype and prototype chain is a model of JS implementation inheritance.
2. The prototype chain is really formed by __proto__ rather than prototype

To understand this sentence in depth, let's take another example to see if you really understand.

  varfunction() {};   var function (){};   = 2000;  
Dog.prototype = animal; var New Dog (); // undefined // -

Why is it? Draw a Memory diagram:

This shows what the problem is, when executing the dog.price, it is found that there is no price attribute, although prototype points to the animal has this attribute, but it does not go along this "chain" to look for. Similarly, when executing tidy.price, there is no such attribute, but __proto__ points to animal, which will follow this chain to find, animal has the price property, so tidy.price output 2000. As a result, the real formation of the prototype chain is __proro__, not prototype.
Therefore, if you specify dog.__proto__ = animal in this way. That Dog.price = 2000.

The final metaphor, though not very precise, may help with the understanding of the prototype.

Father (Function Object), Sir, a big son (prototype), that is your eldest brother, father to your eldest brother bought a lot of toys, when you were born, the relationship between you (__PROTO__) will let you naturally have your eldest brother's toys. Likewise, you, the older son of yours, buy a lot of toys for him, and when you regenerate your son, your youngest son will naturally have all the toys of your big boy. As to whether they will fight, it is not our business.
Therefore, you are from your eldest brother that inherited, confirmed that the "elder brother like Father" Ah!

Source : http://zhangjiahao8961.iteye.com/blog/2070650

The ultimate explanation of JS prototype and 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.