HappyCoding HappyCoding - 2 months ago 4x
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;

// second case
animal = new Animal();

My question: why doesn't the second clear/remove property

in the first case and
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
in this case.

So, why?


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