code show as below:
function Father(){
this.name = true;
this.array = [];
}
Father.prototype.getFatherValue = function(){
return this.property;
}
function Son(){
this.sonProperty = false;
}
//继承 Father
Son.prototype = new Father();
var son1 = new Son();
var son2 = new Son();
The array attribute of Father will be shared by son1 and son2, but the name attribute will not be shared. My understanding is that both son1 and son2 will go to Son.prototype to find the name attribute. The name attribute should also be shared. Why? No?
Because arrays are reference types, for these three instances,
father(new Father()), son1, son2
, theyarray
all save references to[]
this array, so only one of them If it is modified, it will be modified by following the reference to find the array in the memory. What is modified is the same array. Andname = true
, thisname
is a basic type. When distinguishing new instances, an area will be opened in the memory to store its value. Therefore, thename
of the above three instances correspond to different memories. The value of the area, so modifications will not affect each other.After looking at some of the answers above, I thought about it and found that my understanding and my answer were wrong. Keep the original answer and correct it below.
There is no problem about the array. The problem is the name attribute. For
son1 and son2
, they do not have the attributename
, so whennew
, there should be noname
for them. Open up memory space. Only the instancefather
has it. Thename
values of
son1 and son2
are found through the prototype chain search. If son1.name is assigned a value, it is equivalent to adding thename
attribute to the son1 instance. Of course, when printingson1.name
again The value obtained is the namevalue belonging to
son1, and when printingson2.name
, it will go to the prototype chain to findname
. At this time, what is found is thename
value ofFather
, so there are two values Different, may give you the illusion that there is no sharing.It is worth noting that if
son1.array[0] = 1
If the assignment is like this, it will have an impact on the arrays of the three instances. If it isson1.array = [1]
, if the assignment is like this, it will not. Because at this time, array retains a reference to the new array memory address [1].You said the array is shared?
Why does it say that the
name
attribute will not be shared?Prototype chain inheritance means searching along the prototype chain until it finds it and returns this value. If it cannot find it, it returns
undefined
.If we assign a value to Son
At this point, the value of the instance is taken. Only when Son does not have corresponding attributes, it will be searched in the prototype chain.