[JS] Five minutes to understand the prototype constructor prototype chain

[what is a prototype]

The prototype is an attribute of the function object, which defines the common ancestor of the object created by the constructor. The object generated by the constructor can inherit the properties and methods of the prototype, and the prototype is also an object.

[constructor]

To add what I didn’t say in the constructor, we know that person1 and person2 are both instances constructed by the Person constructor. At the same time, we proposed a new concept, constructor, which means construction. After learning es6, I found that this constructor is in In a sense, it is very similar to a class, and will not be explained in detail here.

 
 
 
 
function Person(name, age) {
 this.name = name;
 this.age = age;
}
var person1 = new Person ('hehe', 18);
var person2 = new Person ('haha', 18);

The constructors of person1 and person2 both point to Person.

[prototype]

Person.prototype.sex='male';
console.log(person1.sex);

//male

This Person.prototype is the prototype. It is defined at birth. We said that it points to the prototype object. We added a sex attribute to it with a value of male. This object can be understood as a shared object between person1 and person2. The ancestor of , when it does not have this property, it will look up the prototype chain.

Continuing to explore Person.prototype, we find that there is also an implicit property inside the constructor. It points to the same as those two instances, which is also Person. My understanding is that Person.prototype is also an instance of Person. It is also the ancestor of all instances. .

[__proto__]

I mentioned the prototype chain above, which is why the sex property is accessible on person1. So what is a prototype chain?

When JS creates an object, it generates an implicit property called __proto__, which points to the prototype object of the constructor that created it.
When we output person1.__proto__, we will find that it is Person.prototype, and the prototype is connected to this object through the proto property. When this property does not exist on the object, we will access the proto index to see if there is any on it. If not, continue along the proto looks up.

[Summarize]

1. The constructor Person has a property prototype that points to the prototype (Person.prototype)

2. Instances of constructors person1, person2 have attributes __proto__ and also point to Person.prototype

3.person1, person2 and Person.prototype all have constructor properties pointing to the constructor Person



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325726307&siteId=291194637