An article allows you to get to know the prototype and prototype chain

Each constructor is created when, automatically creates a corresponding object that is the prototype of the object, this function has a pointer to the object. for example:

 The following function creates a person, then person.prototype is the prototype of the object. The prototype object which have a pointer to the function, i.e. person.prototpe.constructor === person (Function)

function person () {

}

Next, create an instance:

const p1 = new person();

Examples of all properties and methods can be accessed prototype object. You can manually add a method to the prototype. person.prototype.name = 'aircraft'

Then print it p1.name // Aircraft

Examples which also has a pointer to the object that is the prototype p1._proto_ === person.prototype (this pointer is the crux of the prototype chain)

Then you may also have a bold idea: Since instances can inherit all the properties and methods of the prototype object, that if I let another function prototype as an example of this function, then another function you can not access the prototype the properties and methods.

Next, and then create a function

function people (){

}

Of course people.prototype is the prototype of the people of this function

So, we put the function prototype as examples person

people.prototype = new person();

Then you create an instance to the people, if the instance name for the aircraft, then explain this inheritance is successful

const pe1 = new perple();

Print it pe1.name // Aircraft

It should be noted that because the prototype people are rewritten, so people prototype constructor prototype constructor is the person

Here is some information I printed in the console, as an auxiliary

 

Guess you like

Origin www.cnblogs.com/hamili/p/10960613.html