A preliminary understanding

I believe as a front-end person; In job interviews, you’re asked about the prototype chain about 8 out of 10 times; So what exactly is a prototype chain? Let’s start with a quick overview

Function Prom() {} console.log(prom.arrname); // Result: Zhang SANCopy the code

You see the code above; Some friends may be surprised; What’s going on here? They don’t seem to have a relationship! In fact, this is the prototype chain, I will say step by step: we learn together

A function

Function Prom() {} console.dir(Prom)Copy the code

Print result:

When we print the constructor, we see that the constructor has a prototype in it. The stereotype has a constructor that points to the Prom constructor;

The constructor points to the prototype chain through prototype; The prototype chain has access to the constructor via constructor

The instance

Function Prom() {} prom.prototype. arrAge = 18 let Prom = new Prom() console.dir(Prom)Copy the code

Print result:

We added an arrAge attribute to the prototype chain on the constructor; By printing the instance, we found that arrAge on the prototype chain was in the proto of the instance.

Instances can access the prototype chain via Proto

ArrName attribute access

Now let’s go back to the original question; Why objects. Prototype properties are accessible in constructors;

Function Prom() {} console.dir(Prom)Copy the code

Print result:

From the above two graphs (they are the same data, just not open);

The first picture:

As you can see from the first figure, the constructor uses prototype to look up the prototype chain. If it doesn’t find one, it looks for proto (object). In the prototype chain if the Object is not found after the data; Object is the highest level, and null is returned

The second picture:

We can see this clearly from the second figure; We have access to the arrName property; Constructor (prototype); constructor (object); constructor (prototype); constructor (object);

Attached a prototype diagram: the picture comes from the network, if there is infringement, please contact to delete

conclusion

1: The constructor accesses the prototype through prototype

2: The constructor creates instance objects from new instances

3: The instance can access the prototype through Proto

4: The prototype can be accessed by construction into the constructor

5: Constructor prototype, object. Prototype can be accessed by proto

If we don’t find the desired properties in the prototype; The prototype looks up the prototype of the next-level object through Proto; Until null is found