The soul of torture

How do you understand prototypes and prototype chains?

answer

A constructor will have a display stereotype attribute, an instance will have an implicit stereotype attribute, and an instance’s cause will have a constructor attribute. Their relationship forms a triangle as shown above. That is, the constructor that generates instance Person has a __Proto__ implicit prototype attribute pointing to the instance prototype Person.prototype, while Person.prototype has a Construtor pointing to a constructor, which has a prototye attribute showing the prototype Point to the instance prototype.

Further down the line, the instance prototype Person.prototype also has a __proto__ implicit prototype property that points to the parent constructor’s prototype instance, just as the __proto__ implicit prototype property of Person points to Person.prototype and Person.proto Protoype type implicitly refers to object. protoype, and then object. protoype implicitly refers to null at the top level, which is equivalent to looking for a method or attribute and not finding __proto__ up to null, thus forming a chain.

So we come to this conclusion:

console.log(Person === Person.prototype.constructor); // true
console.log(person.__proto__ === Person.prototype); // true
console.log(Person.prototype.constructor == Person) // true
Copy the code

extension

What happens when we new an object?

  • Create an empty object obj = {}
  • Binding prototype,obj.__proto__ = Person.prototype
  • Call the Person() function and pass the empty object obj as this, person.call (obj)
  • Return this variable if the Person() function completes its own return of type object, otherwise return this

In the case of Person above, the new Person() instance is obtained by binding the new object prototype, that is, its __proto__ points to Person.protorype, which can be associated with the relationship mentioned above.