Prototype inheritance
When it comes to archetypal inheritance, which is to start with a prototype, let’s briefly review what a prototype is
Prototype Overview: Each function has a prototype, which we call a prototype object
The function’s Prototype property points to the prototype object, and the constructor on the prototype object refers back to the constructor
So as the name implies, archetypal inheritance that is to start with the prototype! !
function Person() {
this.uname = 'Joe'.this.age = 22
}
// Prototype objects
Person.prototype.sex = 'male'
Person.prototype.head = 1
Person.prototype.sayName = function () {
console.log('hello javascript')}function Son() {
this.eye = 2
}
// Assign the instantiation object of the constructor Person to the prototype object of the constructor Son. Then the properties or methods added to the Person prototype are also accessible to the Son instance object. This is exactly what the prototype chain does
Son.prototype = new Person()
// instantiate the object
let per = new Son()
console.log(per)
// You can access properties added on the prototype object
per.sayName()
Copy the code
The sayName method is defined on the prototype of the Person constructor, while the sayName method is defined on the prototype of the Son constructor. Therefore, the sayName method is defined on the prototype of the Son constructor. That’s because of the prototype chain
With per.sayName() you can see the printed result ‘Hello javascript’ on the console
Run the above code, print Son’s instantiation object per, as shown in the figure below. (son.prototype = new Person()) makes Son’s prototype object an instantiation of the constructor Person, new Person(), and has our own property methods on the Person prototype. And its constructor refers back to the constructor Person