JavaScript prototype & Prototype Chain

Prototype chain figure

In the figure, Parent is the constructor and P1 is an object instantiated by Parent. If you’re stunned by this picture, don’t be afraid. Read on for a step-by-step guide to understanding the prototype & Prototype chain

Front knowledge

The concept of prototype and prototype chain is difficult for beginners to understand, but prototype and prototype chain are one of the most important points in JS. From jQuery to Vue, one of the most popular frameworks, prototypes are used everywhere. How can we learn JavaScript prototypes and prototype chains?

To make sense of the prototype and prototype chain, the attributes __proto__, prototype, constructor must be understood. Secondly, you should know the relationship between object and function in JS. Function is actually a kind of object. Finally, you need to know the difference between a function and a constructor. Any function can be a constructor, but you can’t call any function a constructor. Only a function called with the new keyword can be a constructor. Such as:

Var p1 = new Parent(); var p1 = new Parent(); var p1 = new Parent(); // The Parent function is no longer a normal function; it is now a constructor. Because it is called with the new keyword // an instance of the Parent constructor p1 is createdCopy the code

__proto__, prototype, constructor () __proto__, prototype, constructor () __proto__.

Remember that __proto__ and constructor attributes are unique to the object; 2. The prototype attribute is function specific; __proto__ (); __proto__ (); __constructor ();

Next, I will divide the above picture into three pictures and explain the corresponding three attributes respectively.

1. The prototype property

For example, let's simulate a scenario here where the parent class is the master and the child class is the apprentice. A master can have apprentices, and apprentices can have apprentices. Apprentices can get the martial arts taught by the master, and then apprentices can pass them on to their own apprentices. The martial arts master wanted to impart to his apprentices were put into "Prototype", a nirvana in fire. Apprentices and grandchildren go here to learn martial arts. The Prototype property can be thought of as a special storage space for methods and properties used by apprentices and grandsons.Copy the code

It is a function-specific property that you can see pointing from one function to another, indicating that this object is the prototype of the function and the prototype of the instance created by the current function.prototypeInheritance is designed to allow all instances created by a particular function to share properties and methods, or all objects instantiated by a constructor to find common methods and properties. There are theprototypeInstead of creating duplicate property methods for each instance, we create property methods on the constructor’s prototype object. Those that do not need to be shared are created in the constructor. Continuing with the code above, when we want to add a shared attribute to all instances instantiated by Parent,

Parent.prototype.name = "I am a prototype property, all instances can read me ";Copy the code

That’s the stereotype property, but you can also add stereotype methods. How does P1 know that this method exists on his prototype object? Down ↓↓↓

2. The proto properties

The __proto__ attribute is equivalent to the only way to 'Prototype' (' nirvana in Fire ') for 'apprentice' and 'apprentice' to find their own 'master' and 'master's master' to provide their own methods and attributesCopy the code

__proto__ attributes are unique to objects (including functions). As you can see from the diagram, the __proto__ attribute points from one object to another, that is, from one object to that object’s prototype (also known as the parent). Obviously what it means is to tell us who the prototype object of an object is. Properties and methods added to Parent. Prototype are called prototype properties and methods, and instances of the constructor can be called. How can properties and methods on the constructor’s protoobject be associated with instances of the constructor via the __proto__ property? Each object has a __proto__ attribute that points to the object’s prototype.

p1.__proto__ === Parent.prototype; // true
Copy the code

__proto__ is usually called an implicit prototype, and prototype is usually called an explicit prototype, so we can say that the implicit prototype of an object refers to the explicit prototype of that object’s constructor. So the property methods we defined on the explicit stereotype are passed to the constructor instance via the implicit stereotype. This makes it easy for the instance to access the methods and properties on the constructor prototype. __proto__ attributes are unique to objects (including functions). Parent. Prototype is also an object. To whom?

Parent.prototype.__proto__ === Object.prototype; //true
Copy the code

As you can see, the implicit prototype Object on the constructor’s prototype Object points to the prototype Object of Object. Then Parent’s prototype Object inherits Object’s prototype Object. From this we can verify a conclusion that everything inherits from Object.prototype. That’s why we can instantiate an object and call properties and methods that don’t exist on that object. Such as:

// We don’t define any method attributes in Parent, but we can call them

p1.toString(); //hasOwnProperty, etcCopy the code

We can call a lot of methods that we haven’t defined, but where did those methods come from? P1.__proto__ : Parent. Prototype: p1.__proto__ : Parent. Prototype: Parent. __proto__ : Object. Prototype: Parent. Prototype. __proto__ The toString method is found in this layer. Return this method for use by P1. __proto__ === null; object.prototype. __proto__ == null; This is why undefined is returned when accessing a nonexistent property of an object.

3. The constructor property

The constructor attribute lets the "students" and "grandsons" know who created themselves, here is not "master" but their parents, parents created themselves, parents created by the previous generation,... Function() [Nu Wa].Copy the code

Constructor is an object property that points from an object to a function as seen in the diagram. The function pointed to is the object’s constructor. Every object has a constructor. For example, p1 is an object. Who is the constructor of P1? Let’s print it out.

console.log(p1.constructor); / / ƒ Parent () {}Copy the code

It is clear from the output that this is the Parent function. We’ve already said that functions are objects, so does the Parent function have a constructor? Apparently there is. Print it again.

console.log(Parent.constructor); ƒ Function() {[model]}Copy the code

The output shows that the Parent Function’s constructor is Function(), which is not surprising because each time we define a Function we actually call new Function(). The two effects are the same.

var fn1 = new Function('msg','alert(msg)');
function fn1(msg){
    alert(msg);
}
Copy the code

So let’s go back and print function.constructor again

console.log(Function.constructor); ƒ Function() {[model]}Copy the code

Function is the root constructor of all functions. Function is the root constructor of all functions. Here we have a glimpse of the constructor property, which points from an object to a function that is the object’s constructor. The constructor property of p1 points to Parent, which is the constructor of P1. Similarly, Parent’s constructor property points to Function, which is the Parent’s constructor, and then verifies that Function is the root constructor.

conclusion

Seeing this, I believe that you have a certain understanding of the prototype and prototype chain, students who have not special understanding do not worry, prototype prototype chain and closure are the most difficult parts of JS, requiring a certain amount of technical accumulation and time precipitation. Open the article and read it once a day, and draw the picture of the prototype chain by yourself, because some of the principles can not be said, and have to rely on their own understanding. Short step without thousands of miles without small streams into rivers and seas.