Reputation: 25
The code is below:
function A() {
this.name = "kl";
this.obj2 = { a: 1 };
}
A.prototype.city = "china";
A.prototype.obj = {age: 30};
var a = new A();
var b = new A();
a.name = "kobe";
a.obj.age = 20;
a.city = "American"
a.obj2.a = 30;
console.log(b.name); // k1
console.log(b.city); // why china ?
console.log(b.obj); // when b.city = china, why b.obj = {age: 20}
console.log(b.obj2); // {a: 1}
My opinion is that a and b has its own this, so how you edit this[property] you can't change b its own this.value;
property declare so share property ? is right ? but when obj is change will effect b.obj, when city change will not effect b.city ?
Upvotes: 0
Views: 80
Reputation: 4438
Let's go through this line by line:
A.prototype
points to an object.var a = new A();
name
and obj2
which have values kl
and { a: 1 }
function A
, the function actually runs return this;
, which literally returns the object created to be assigned to a
.var b = new A();
does the same as abovea.name = "kobe";
, you're modifying the value from kl
to kobe
a.city = "American";
, you're creating a new property city
on a
itselfa.obj2.a = 30;
, you're also only modifying a value.a.obj.age = 20;
, something is different
a
doesn't have the property obj
on itself, so it goes up the prototype chain to the object A.prototype
points to, and finds the property obj
, so this line of code is actually modifying that obj
, and changes the value of obj.age
from 30 to 20. b.name
, since b
has property name
with value kl
, so it prints kl
b
doesn't have the property city
on itself, so it goes up the prototype chain to the object A.prototype
points to and see if it can find one, which it does, as previously you ran A.prototype.city = "china";
, so it prints china
.console.log(b.obj);
is run, b
goes up to the prototype chain and find obj
on the object A.prototype
points to, so it prints {age: 20}
Upvotes: 1
Reputation: 816442
Both objects have city
and obj
in their prototype chain. However, if you do a.city = "American"
you are creating a new property city
on a
itself, shadowing the property city
in the property chain.
Assigning to a property will (almost) always create that property on the object itself.
a.obj.age = 20;
however reads (not assigns!) the object referenced by a.obj
and updates its age
property. a
and b
have the same prototype and thus a.obj
and b.obj
resolves to the same object. If the object is mutated in any way it will affect a
and b
in the same way.
Structure from the Chrome console:
Upvotes: 4