goonerify
goonerify

Reputation: 1756

Why do Javascript classes reference the same constructor?

I'm trying to reflect a javascript object on a class but for some reason, it seems the constructor for all javascript classes point to the same reference object in memory. This means that i cannot reflect 2 different objects on 2 separate javascript classes because the first one just gets overwritten by the second.

require('reflect-metadata');

class Class1 {}

class Class2 {}

class Sub1 {}

class Sub2 {}

Reflect.defineMetadata("METADATA", Sub1, Class1.constructor);
Reflect.defineMetadata("METADATA", Sub2, Class2.constructor);

console.log(Class1.constructor === Class2.constructor); // true
console.log(Reflect.getMetadata('METADATA', Class1.constructor)) // [Function: Sub2]

const cls1 = new Class1();
const cls2 = new Class2();

Reflect.defineMetadata("METADATA", Sub1, cls1.constructor);
Reflect.defineMetadata("METADATA", Sub2, cls2.constructor);

console.log(cls1.constructor === cls2.constructor); // false
console.log(Reflect.getMetadata('METADATA', cls1.constructor)) // [Function: Sub1]

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

Upvotes: 0

Views: 49

Answers (1)

jfriend00
jfriend00

Reputation: 707786

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.

Upvotes: 1

Related Questions