I don’t understand why fooA and fooB outcome different.
var foo = function(){}
fooA = new foo();
foo.prototype.x = 1;
foo.prototype = { y: 2, z: 3};
console.log(fooA.x, fooA.y, fooA.z);// 1, undefined, undefined
fooB = new foo();
console.log(fooB.x, fooB.y, fooB.z);// undefined, 2, 3
-
does foo.prototyp = {} override the method defined in front of it?
-
Why fooA is state in front of prototype.x, it inherit the result, but not y and z?
The reason for that behavior is that you make
foo.prototypepoint to a new object when usingfoo.prototype = { y: 2, z: 3};, and existing objects’ prototypes don’t change when the constructor’sprototypeproperty is set to a new value.A line-by-line explanation of what happens:
var foo = function(){}foo.prototypeis initialized as an empty object (we shall call this objectA).fooA = new foo()fooAis set to a new foo object, it has its prototype set tofoo.prototype(A).foo.prototype.x = 1Because
fooA‘s prototype is the same object asfoo.prototype,fooA.xbecomes 1. In other words,Agets the propertyx = 1.foo.prototype = { y: 2, z: 3};We create a new object that has the properties
y = 2andz = 3. We shall call this objectB.foo.prototypeis set to the new object.console.log(fooA.x, fooA.y, fooA.z);fooA‘s prototype is stillA, which only has thex = 1property.fooB = new foo();We create a new foo object whose prototype is
B.console.log(fooB.x, fooB.y, fooB.z);fooB‘s prototype isB, which has the propertiesy = 2andz = 3, but not the propertyx.