No. x
is an instance of A
. When you try to access x.attr
initially, its prototype, A
, does not have an attribute named attr
. Thus, it is equivalent to calling x.i_want_something_which_does_not_exist
, which returns undefined
. But after you assign A.prototype.attr
, all instances of A
will share that value. For example,
function A(){
}
var x = new A();
var y = new A();
document.write(x.attr+"<br>"); // undefined
document.write(y.attr+"<br>"); // undefined
A.prototype.attr = 1;
document.write(x.attr+"<br>"); // 1
document.write(y.attr+"<br>"); // 1
Edit: Here is an example of three instances:
function printValues(x, y, z){
document.write("x.attr="+x.attr+", y="+y.attr+", z.attr="+z.attr+"<br />"); // Although I strongly recomment you to never use document.write
// https://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice
}
function A(){
}
var x = new A();
var y = new A();
var z = new A();
printValues(x, y, z);
A.prototype.attr = 1;
printValues(x, y, z);
y.attr = 2;
printValues(x, y, z);
produces:
x.attr=undefined, y=undefined, z.attr=undefined
x.attr=1, y=1, z.attr=1
x.attr=1, y=2, z.attr=1
Note that after running y.attr=1
, y.attr
has a different reference than x.attr
and z.attr
, which, by the way, still share same reference.
"); `, x's prototype don't have property `attr`, so x's prototype is reallocated? – gaussclb Jul 30 '18 at 13:14