Search code examples
javascriptobjectprototype

Why doesn't prototype object change?


As far as I know, objects are assigned by the reference (they are not copied). Therefore, if changes in an object occur via one link, then they occur via another.

let a = {
  writer: 'J.K. Rowling',
  singer: 'Beyonce',
  politician: 'A. Merkel'
};

let b = a;
delete a.politician;

console.log(b); //there's no politicaian as well

Then... why do things work differently here? prototype is one object, so changes should be everywhere (by 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; //reassignment

console.log(Object.getPrototypeOf(obj)); //userInfo

And here, for example, changes occur. 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'; //reassignment

    console.log(Object.getPrototypeOf(obj));

Why is that so? Why do changes happens in some cases and not in others?


Solution

  • In your examples you are doing two different things:

    • Reassign the prototype: will make new objects inherit from the new prototype, but not previously created objects. The old prototypes are being referenced directly by the old objects, so reassigning Constructor.prototype has no effect on them
    • Mutate the prototype: changes the prototype of existing and future objects