why do javascript classes reference the same constructor?

I’m trying to understand why non-instance JavaScript objects seem to point to the same location in memory and reference the same base constructor

The class name IS the constructor itself. So, if you want a unique reference to each class’s constructor, then use the class name itself.

On the other hand, Class1 is an already constructed Function object and thus Class1.constructor is the constructor for that Function object as is Class2.constructor so thus they each point to the same Function object constructor. That’s why:

Class1.constructor === Class2.constructor
Class1.constructor === Function.prototype.constructor
function f() {}
Class1.constructor === f.constructor

If you want the constructor for Class1, you can reference it with either Class1 or with Class1.prototype.constructor, not with Class1.constructor.

So, you will find that:

Class1 !== Class2
Class1 === Class1.prototype.constructor
Class1.prototype.constructor !== Class2.prototype.constructor

Why do Javascript classes reference the same constructor?

Because Class1.constructor is the constructor for the already constructed Class1 Function object, not the constructor for your class. The constructor for your class would be Class1 or Class1.prototype.constructor.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top