The reason for this behavior is that when using foo.prototype = { y: 2, z: 3}; foo.prototype = { y: 2, z: 3}; you point foo.prototype to a new object, and prototypes of existing objects do not change when the prototype constructor property is set to a new value.
A step-by-step explanation of what is happening:
var foo = function(){}
foo.prototype initialized as an empty object (we will call this object A ).
fooA = new foo()
fooA installed in a new foo object, it has a prototype installed on foo.prototype ( A ).
foo.prototype.x = 1
Since the prototype fooA is the same object as foo.prototype , fooA.x becomes 1. In other words, A gets the property x = 1 .
foo.prototype = { y: 2, z: 3};
We create a new object with the properties y = 2 and z = 3 . We will call this object B foo.prototype set to a new object.
console.log(fooA.x, fooA.y, fooA.z);
fooA prototype is still A , which has the property x = 1 .
fooB = new foo();
We create a new foo object whose prototype is B
console.log(fooB.x, fooB.y, fooB.z);
fooB prototype B that has properties y = 2 and z = 3 , but not property x .
source share