js - prototype and prototype chain

I read a lot of interview questions recently, and saw that this js prototype is a common test point, so I summarized some knowledge points in this area to share with you. In fact, the prototype is the same thing.

The result is shown in the figure below:

  1. prototype

Prototypes can be divided into explicit prototypes and implicit prototypes

1.1 Explicit Prototypes

Explicit prototype prototype
Only functions will have the concept of explicit prototype, and there is a constructor in the prototype that points to this prototype.
        所以——————test=== test.prototype.constructor

1.2 Implicit Prototypes

Implicit prototype __proto__
Only the instance object of the constructor has the concept of implicit prototype, and the implicit
prototype of the instance object of each constructor points to the explicit prototype of the constructor So ————— obj.__proto__ === test.prototype prototype: Each function is created through the new method, such as built-in functions like Number and String, and its prototype itself has many methods. For example, for Number, is Number.isNaN also inherent to it? method, then why we can use it directly, it is because his prototype has these methods, to put it bluntly, your game character itself has this skill when you play games (although I don’t play games either), and we The prototype is a truth, the prototype is to let us use some methods of the function itself




2. Prototype chain

Prototype chain: As mentioned above - the implicit prototype of the instance object of each constructor points to the explicit prototype of the constructor, and also said, which methods are in his prototype, so how do we know the prototype of the
function Does it have this method? Just like if you want to check if something exists, you need to start searching first to see if it exists. If it does not exist, we are doing other operations, and the
same is true in the prototype. First, check whether there is this attribute in the prototype of the function. If you don't follow this rotten theorem - the implicit prototype of the instance object of each constructor points to the explicit prototype of the constructor, just keep searching until the result of __proto__ is null at the end,
if If you don’t have it,
then you don’t have it, but how do you want to use it? At this time, your brain hole will be opened. You can add it yourself, but don’t add methods blindly, because it may cause unpredictable errors.

I personally feel that there are so many things, if there are any friends who need to add, please leave a message

Guess you like

Origin blog.csdn.net/Bonsoir777/article/details/129223652