What is prototype and prototype chain in JS?

What is a prototype?

       The prototype is that each function will have a prototype attribute after the declaration, which points to the prototype object of the constructor. We call the prototype an explicit prototype, and there is a __proto__ attribute in each instantiated object, which points to it The prototype prototype object of the constructor, __proto__ is also called the implicit prototype. In the prototype prototype object, there is a constructor attribute pointing to the constructor associated with it.
For example the following code:

class Student {
    
    
    constructor(name, number) {
    
    
        this.name = name
        this.number = number
    }
    say() {
    
    
        console.log(`介绍:姓名 ${
      
      this.name} 学号 ${
      
      this.number}`)
    }
}

// 通过new关键字去实例化对象
const stu = new Student('小明', 123)
stu.say()

Its prototype structure diagram is as follows:

insert image description here
Note: class in es6 is syntactic sugar, its essence is still a function
insert image description here

What is the prototype chain?

       When accessing the properties of an object, it will first search in the properties of the object itself. If it can be found, it will return the value of the property. If it cannot be found, it will search in the implicit prototype of the object's __proto__ (ie The prototype of the object constructor), if you still can’t find it, you will continue to search in the prototype object pointed to by the __proto__ attribute of the prototype object of its constructor, and you will search layer by layer until you find Object.prototype The top-level prototype object is such a search method that forms a chain structure, which we call a prototype chain.

insert image description here

Guess you like

Origin blog.csdn.net/m0_37873510/article/details/126393865