Short answer js prototype and prototype chain

prototype: prototype object

  Each function has a prototype attribute,

  Every object (except null) is associated with another object when it is created,

  This object is what we call the prototype, and every object "inherits" properties from the prototype.

  But if the object itself overwrites the property, then the new property value will be adopted

 

  Code display:

// 构造函数
function Person() {

}

// prototype是函数才会有的属性
Person.prototype.name = 'Kevin';

// 创建对象
var person1 = new Person();
var person2 = new Person();

// 对象会继承原型中的属性
console.log(person1.name) // Kevin
console.log(person2.name) // Kevin
  •   The attribute name is created in the prototype

  •   No properties are defined after the object is created.

  •   By reading the name, you can still get the value, which is the value of the name in the prototype

  •   Therefore, the prototype itself is an object, which can be used to store the common attribute values ​​of the instance object , or the default attributes

  •   The purpose is to reduce unnecessary memory consumption

 

proto: Get your own prototype

 

    The properties of every object will point to the prototype of this object.

    Stored is the address of the prototype.

function Person() {

}
var person = new Person();
console.log(person.__proto__ === Person.prototype); // true

 

  Prototype builder

   Each prototype has a constructor attribute that points to the associated constructor function instance prototype points to the constructor function

   

function Person() {

}
console.log(Person === Person.prototype.constructor); // true

 

 

Prototype chain

The object uses __proto__ to query the prototype of its own type.

Can be traced back to the prototype of Object

If the Object prototype is queried further up, it is null.

And this traceback is the prototype chain

Guess you like

Origin blog.csdn.net/wanghongpu9305/article/details/112986131