Reputation: 75
i get absolutely the same results whether i use "this.value=1;" inside the constructor function or just put property value inside prototype of function constructor - "MyClass.prototype.value =1;"
function MyClass() {
//this.value=1;
}
MyClass.prototype.value =1;
var a = new MyClass();
document.write(a.value + "<br>");
a.value=13;
document.write(a.value + "<br>");
var b = new MyClass();
document.write(b.value);
result is :
1
13
1
since last value is 1, obviously every object (a,b) get it's own copy of value inside it's own memory block so what exactly is the use of prototype values if they are not shared between objects?
Upvotes: 1
Views: 213
Reputation: 359786
Your test is specious. Prototype values are shared between values, but in writing a.value = 13
, you've shadowed the MyClass.prototype.value
property on a
. Try this on for size:
function MyClass() {}
MyClass.prototype.value = 1;
var a = new MyClass();
document.write(a.value + "<br>");
a.__proto__.value=13;
document.write(a.value + "<br>");
var b = new MyClass();
document.write(b.value);
(demo)
Object property lookups travel up the prototype chain until either the prototype is null, or a property with the specified name is found. In your original test a.value = 13
causes lookups on a.value
to end with a
– since there is a property called value
on that object – before ever reaching the prototype.
More reading:
Upvotes: 6
Reputation: 150030
"I get absolutely the same results"
Only because you don't yet know how to interpret your test results.
All instances share the properties from the prototype, but instances can have instance properties with the same names as those of the prototype.
So when you say a.value = 13
you are creating a property on the a
instance but the prototype value
property is still 1
.
If you instead said MyClass.prototype.value = 13
you'd see that both a.value
and b.value
report 13
even if you change the prototype's value
after creating a
and b
.
Upvotes: 2