Differ between foo.prototyp.x = & foo.prototype = {x:}

I do not understand why fooA and fooB are 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 before it?

  • Why is fooA the state before prototype.x, it inherits the result, but not y and z?

+4
source share
3 answers

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 .

+4
source

Consider

 var foo = function(){} fooA = new foo(); foo.prototype.x = 1; console.log(fooA.__proto__) // {x:1} foo.prototype = { y: 2, z: 3}; console.log(fooA.__proto__) // still {x:1} 

The prototype of the object is assigned at creation time (when calling new ) and does not change after that. See here for more details.

+2
source

it

 F.prototype = { ... }; 

replaces the prototype object of constructor F The old prototype object is replaced with the new prototype object.

Instances of F

 var f = new F(); 

have an implicit prototype reference that references the prototype object of the F constructor. However, this link is set during instance initialization.

for instance

 var f1 = new F(); F.prototype = { ... }; var f2 = new F(); 

Here, the prototype reference f1 refers to the old prototype object, and the prototype reference f2 refers to the new prototype object.

Note that even if the F.prototype object F.prototype been replaced, the old prototype object will continue to exist if there is at least one instance of F whose prototype reference refers to it.

+1
source

Source: https://habr.com/ru/post/1389278/


All Articles