mercredi 28 octobre 2020

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





Aucun commentaire:

Enregistrer un commentaire