Let's look at the prototypes in JavaScript: "Prototypes are also an object, and prototypes can be used to implement inheritance ... “
For prototypes, constructors, and relationships between instances: "each (constructor) function has a prototype property, and the prototype object contains a pointer to the constructor, each containing a pointer to the prototype object. ”
As an example:
1 function Student (name) {2 this. Name = name; 3 }4 varnew Student ("Xiao Ming");
The Student function has a prototype property that points to Student's prototype object. The student prototype object contains a constructor property and a __proto__ property. The constructor property points to the student function, __proto__ to the prototype of object (all objects in JavaScript inherit object). Student function:
In the code we also create an instance of the student function Stu, which will have a pointer __proto__ to the student prototype object.
Note: There will be one more name attribute in Stu, and the property is in the instance, not the function, or the prototype of the function, which is very error-prone. Stu Real Example:
So, the whole object of the previous example is:
Prototype chain: If you assign an instance of a constructor (A) to a prototype of another constructor (b), then function B, instance of function A, and function A will form a prototype chain. The instance of B inherits all the properties and methods of a.
If we assign the Stu to the prototype of other objects at this point, we can see that the Red Line part will form a prototype chain.
Examples of inheritance using a prototype chain:
functionPerson () { This. Hasfriends =true; This. Friends = ["David"]; } Person.prototype.getHasFriend=function() {alert ( This. Hasfriends); } functionStudent () { This. HASGF =false; } Student.prototype=NewPerson (); Student.prototype.getScore=function() {alert ( This. HASGF); } varStu =NewStudent (); Stu.getfriends (); Stu.friends.push ("Lily"); varNewstu =NewStudent (); alert (newstu.friends);
Javascript Prototypes and prototype chains