Home > Article > Web Front-end > In-depth understanding of prototype and inheritance in JavaScript_Basic knowledge
Generally speaking, an object in JavaScript is a pointer to a prototype and a list of its own properties. JavaScript uses the concept of copy-on-write when creating objects.
Only the constructor has the prototype attribute. Prototype chain inheritance is to create a new pointer pointing to the prototype attribute of the constructor.
The reason why the prototype attribute is special is due to the traversal mechanism when reading attributes in JavaScript. Essentially it's just an ordinary pointer.
Constructors include:
1.Object
2.Function
3.Array
4.Date
5.String
Let’s give some examples
Our purpose is to express
1. Indicate that Person inherits from Animal
2. Indicate that p2 is an instance of Person
Let’s modify the pointing of the prototype attribute so that Person can obtain the methods in the prototype attribute in Animal. That is, Person inherits from Animal (people are beasts)
But if we modify it like this
Person.prototype = new Animal();
Person.prototype.constructor = Person;
At this time p2. The consturctor is right, it points to Person, indicating that p2 is an instance of the Person class, but a new problem arises. At this time, goal 2 has been achieved, but goal 1 has not been achieved.
Purpose 1 and Purpose 2 are contradictory to each other at this time, because prototype expresses two contradictory meanings at this time,
1 indicates who the parent class is
2 is copied as the prototype of its own instance
Therefore, we cannot directly use the prototype attribute to indicate who the parent class is, but use the getPrototypeOf() method to know who the parent class is.
It separates these two concepts
Finally to summarize:
When the code var p = new Person() is executed, new does the following things:
Create a blank object
Create a pointer to Person.prototype
Pass this object into the constructor through the this keyword and execute the constructor.
If Person.prototype = Animal.prototype is used to indicate that Person inherits from Animal, the instanceof method will also show that p is also an instance of Animal and return true. The reason why this method is not used is because of the following two reasons:
1.new creates a new object, which avoids that setting Person.prototype.constructor = Person will also cause the value of Animal.prototype.constructor to change to Person, but dynamically gives this newly created object a constructor instance attribute, so that the attribute constructor on the instance covers Animal.prototype.constructor, so that Person.prototype.constructor and Animal.prototype.contructor are separated.
2. The attributes of Animal’s own this object cannot be passed to Person
By using the hasOwnProperty() method, it is clear when accessing instance properties and when accessing prototype properties.