Summary of JavaScript Prototype

The prototype property of JavaScript is an object, and each function automatically obtains this property after definition. Its initial value is an empty object (Object), as shown in the following example:

A new constructor named Dog has been created above, with a prototype of an object. The constructor and prototype are default built-in properties when creating a prototype. When creating a new object, these two properties will be included, regardless of whether it is empty or not. For example:

It should be noted that the created object does not have a prototype attribute, but each object has a hidden property of a prototype, which functions similarly to a prototype and can point to the prototype object of its constructor. It sounds awkward, but it’s more intuitive to just look at the example. Let’s take a look at the more properties of the object from the example just above:

It can be seen that the prototype object of the constructor of object a and the hidden proto property of object a point to the same object.

From the above examples, we can make an extension that since each object has a constructor, and each constructor has a prototype object, the prototype itself is an object, and it will definitely have its own constructor, giving it a feeling of being trapped in a loop. However, JavaScript will not let this happen. The father of all objects is an Object () object, which is connected layer by layer through the prototype chain, That is the concept of a prototype chain in JavaScript.

Below, we will deepen our understanding of the prototype chain through a more intuitive example:

Let’s take a look at the first scenario. We have created a constructor for a Dog and used it to create an object named Rusty. You can see that Rusty has the attributes (tail) that the Dog function defines, as well as the attributes (say function) from the prototype of the Dog:

Not only do you have the properties in Dog and Dog. prototye, but you can also see the relationship between the hidden property proto of trusty and Dog. prototype, as well as the relationship between the hidden properties of Dog and Dog. prototype and Function() and object() objects.

Another scenario is to assign the value of Dog-prototype to a new object, where the constructor property of Dog-prototype will change its orientation, and the previously created object trusty will not have new properties of Dog-prototype, but the old properties will still be retained:

As can be seen, the Dog.prototyp.inspector no longer points to the Dog, while the trusty can still retain the properties obtained from the original creation. At this point, if you are creating a new object, you can obtain the properties of the new Dog. prototype, such as the following:

Summarize the above situation into a link diagram, which can clarify the relationships more clearly (hand drawn work):