Study notes-prototype object and prototype chain


All variables and U objects in javascript can be considered to be created directly or indirectly by a certain function of new.

Constructor : The new function is called the object's constructor.

Prototype object : There is a prototype property on the constructor, which is called the prototype object of the object. All instances (objects) coming out through new will share the methods and properties on the prototype object.

E.g: 

var arr = new Array();    // Array()是构造函数, arr是实例(对象)
Array.prototype.a = 1;    // Array.prototype是原型对象
console.log(arr.a);       // 结果是:1, arr共享原型对象上的方法和属性

When an object calls a method, it will first look for the method in itself. If not, it will go to the prototype chain to find its prototype. If it cannot find it, it will continue to look for the prototype of the prototype, step by step.

Prototype chain : A chain is formed between prototype objects. For example, in the above example, when using the method in the array, it will first go to Array.prototype to find if there is any, and then go to the prototype object Object.prototype of its prototype object to find it, if not found, go to the prototype of Object prototype null Go up and find. This forms a prototype chain.

 E.g:

var arr = new Array();
Object.prototype.b = 2; 
Array.prototype.a = 1;
console.log(arr.b); // 2
// 输出arr.b是先去Array.prototype找有没有属性b,再去Object.prototype找

The prototype object refers to the object pointed to by the prototype. For example, the prototype object of an array is the object pointed to by Array.prototype.

The prototype object will have a default constructor attribute to point to the function itself. For example, the result of array.constructor is its constructor Array().

The prototype object and prototype chain are mainly used to implement inheritance.

Example, the structure diagram of the constructor and the prototype object is:

 

Guess you like

Origin blog.csdn.net/qq_41339126/article/details/109428967