First, understand a few rules:

1. Any function has the prototype property, called display prototype, which is an object.

2. The instantiated object has an implicit prototype __proto__ property value that points to the explicit prototype property value of its constructor. It’s also an object.

Here’s the code:

Person.prototype.name = 'snail'
function Person(){
// The process that happens when new
//var this = {
// __proto__: person. prototype // This explains why child objects can access the parent object's properties and methods
/ /}
//return this
    }
    
    var person = new Person()
    console.log(person.__proto__ === Person.prototype); //true
    console.log(person.__proto__.name); / / the snail
    console.log(person.name); / / the snail
Copy the code

Next let’s see if the __proto__ pointing of the child object can be changed

Person.prototype.name = 'snail'
function Person(){}var obj = {
    name:'wn'
}

person.__proto__ = obj
console.log(person.name)//wn 
Copy the code

If you look at the result, you can see that you’ve changed the person prototype to point to another object, obj, so you don’t have to go to the Person prototype

If I change the value on the parent object prototype, will the value of the child object change

Person.prototype.name = 'snail'
function Person(){}var person = new Person()
Person.prototype.name = 'and'

console.log(person.name)/ / the snail
Copy the code

It turns out that nothing has changed, and as you can imagine, the object is instantiated independently

Can a child object change the value of its parent?

Person.prototype.name = 'snail'
function Person(){}var person = new Person()
person.name = 'and'
console.log(Person.prototype.name)/ / the snail
console.log(person.__proto__.name)/ / the snail
console.log(person.name) / / quietly
Copy the code

It is obvious that the child object cannot modify the attributes of the parent object, so the child object adds a new attribute name, overwriting the inherited name. This phenomenon is called masking. In plain English, the child object overwrites the inherited element

__proto__ is used to add attributes and methods to the child object, and other children are not accessible, but the parent object is accessible to all attributes of the child object

Person.prototype.name = 'snail'
function Person(){}var person1 = new Person()
var person2 = new Person()
person1.__proto__.age = 18
person2.__proto__.sex = 'woman'

console.log(person1.age) / / 18
console.log(person2.age) / / an error

console.log(person1.sex) / / an error
console.log(person2.sex) / / women

console.log(Person.prototype.age)/ / 18
console.log(Person.prototype.sex) / / women
Copy the code