Home>

As far as I know, objects are assigned by reference (! Not copied). Therefore, if changes in the object occur on one link, then they occur on the other.

Let A= {
  Writer: 'J.K. ROWLING ',
  Singer: 'Beyonce',
  Politician: 'A. Merkel '
};
LET B= A;
delete a.politician;
Console.log (b); //There is also no Politicaian 

Why then everything works a little differently? In the same principle Prototype. It is one object, so the changes should be everywhere (in two links).

Let userinfo= {
    Name: 'kira',
    Surname: 'Li',
    Age: 25,
    Country: 'USA',
    City: 'La'
};
Let Food= {
    Fruit: 'Apple',
    Vegetable: 'Cabbage',
    Pastry: 'Bun',
    DRINK: 'WATER'
};
FUNCTION CONSTRUCTOR () {};
Constructor.prototype= userinfo;
Let OBJ= New Constructor;
Constructor.prototype= Food; //Refrigerate happened
Console.log (Object.getPrototypeof (OBJ)); //All also UserInfo 

And here, for example, the change occurs. Why?

Let userinfo= {
        Name: 'kira',
        Surname: 'Li',
        Age: 25,
        Country: 'USA',
        City: 'La'
    };
    Let Food= {
        Fruit: 'Apple',
        Vegetable: 'Cabbage',
        Pastry: 'Bun',
        DRINK: 'WATER'
    };
    FUNCTION CONSTRUCTOR () {};
    Constructor.prototype= userinfo;
    Let OBJ= New Constructor;
    Constructor.prototype.name= 'klara'; //Refrigerate happened
    Console.log (Object.getPrototypeof (OBJ)); 

Why so? Why in some cases there is a change in the object, and in some no?

  • Answer # 1

    In fact, everything corresponds to the assignment by reference.

    function constructor () {};
    Constructor.prototype= userinfo;
    Let OBJ= New Constructor;
    Constructor.prototype= Food; //Refrigerate happened
    

    can be represented as:

    const OBJ1= {A: {B: 1}}; //This is our designer with a prototype in "a".
    Const OBJ2= {C: OBJ1.A}; //This is the creation of an instance with reference to the prototype.
    //OBJ2.C is assigned to OBJ1.A,
    //But essentially assigned a link to {B: 1}
    //OBJ2.C is no longer associated with OBJ1.A, but is associated with {B: 1}
    OBJ1.A= {D: 2};
    //OBJ1.A Now refers to {D: 2}
    //But OBJ2.C still refers to {B: 1}
    Console.log (OBJ2.C); //{B: 1}
    
  • Answer # 2

    In fact, everything corresponds to the assignment by reference.

    function constructor () {};
    Constructor.prototype= userinfo;
    Let OBJ= New Constructor;
    Constructor.prototype= Food; //Refrigerate happened
    

    can be represented as:

    const OBJ1= {A: {B: 1}}; //This is our designer with a prototype in "a".
    Const OBJ2= {C: OBJ1.A}; //This is the creation of an instance with reference to the prototype.
    //OBJ2.C is assigned to OBJ1.A,
    //But essentially assigned a link to {B: 1}
    //OBJ2.C is no longer associated with OBJ1.A, but is associated with {B: 1}
    OBJ1.A= {D: 2};
    //OBJ1.A Now refers to {D: 2}
    //But OBJ2.C still refers to {B: 1}
    Console.log (OBJ2.C); //{B: 1}