84669 person learning
152542 person learning
20005 person learning
5487 person learning
7821 person learning
359900 person learning
3350 person learning
180660 person learning
48569 person learning
18603 person learning
40936 person learning
1549 person learning
1183 person learning
32909 person learning
As shown above, the __proto__ of instances p1 and p2 point to the same prototype object Person.prototype,
__proto__
p1
p2
Person.prototype
Execute p1.age=12, why p1.age does not change to 12, but remains the original 0
p1.age=12
p1.age
12
0
p1.age will not change the value of the prototype. p2 has no age attribute. It will look up along the prototype chain and find the age in Person, so p2.page is equal to Person.prototype.age
Because p1.age modifies the attributes on p1 instead of the attributes on the prototype.
p1.age = 12 will only assign a value to the age of p1, but not to the age of Person, so the age of p2 is not assigned, so it is still 0 on the prototype
p1.age = 12 actually adds an attribute age with a value of 12 to p1. When accessing p1.age, this attribute will be accessed directly without going to the prototype chain to find age. , if you want to realize that p1 and p2 are changed, you can write like this p1.__proto__.age = 12
p1.age = 12
age
age.
p1.__proto__.age = 12
p1.age will not change the value of the prototype. p2 has no age attribute. It will look up along the prototype chain and find the age in Person, so p2.page is equal to Person.prototype.age
Because
p1.age
modifies the attributes on p1 instead of the attributes on the prototype.p1.age = 12 will only assign a value to the age of p1, but not to the age of Person, so the age of p2 is not assigned, so it is still 0 on the prototype
p1.age = 12
actually adds an attributeage
with a value of 12 top1
. When accessingp1.age
, this attribute will be accessed directly without going to the prototype chain to findage.
, if you want to realize that p1 and p2 are changed, you can write like thisp1.__proto__.age = 12