HappyCoding HappyCoding - 3 months ago 6
Javascript Question

Update __proto__ property after updating new reference of an Object



class Animal {
constructor() {

}
}

let animal = new Animal();

// first case
animal['__proto__']['__id'] = 1;
console.log(animal['__proto__']);

// second case
animal = new Animal();
console.log(animal['__proto__']);





My question: why doesn't the second clear/remove property
__id
from
__proto__
?

animal
in the first case and
animal
in the second case reference to same class (Object). But in OOP, when I reset the instance of an object, all properties would be reset, too. It's not for
__proto__
in this case.

So, why?

Answer

The idea behind prototypes is that all instances created by a given constructor (which means all instances of a given class, if you're using ES6 classes) share a single prototype object. It's just a single object that exists and can be modified: a new one prototype object isn't made every time a new instance is created, because the point is that it's shared.

These two lines are equivalent; though the second is the preferred way of doing it*.

animal["__proto__"].foo = "foo";
Animal.prototype.foo = "foo";

If you're trying to set an id, something that should be unique to the instance, then just set it on the object itself, and not on the prototype.

* __proto__ was only even standardized as part of the language in ES6; and only then because all the browsers implemented it anyway