Home > Software engineering >  Pass class contructor as function in another class
Pass class contructor as function in another class

Time:04-07

I have two classes (let's say class1 and class2) and I would like to make class2 part of class1 and instantiate it.

What I would like to manage is to:

const class1 = new Class1();
const class2 = new class1.Class2();

Any ideas?

CodePudding user response:

You cannot have that kind of initialization, but you can have a similar way through a function call

class Class2 {
   test() {
       console.log('testing class 2')
   }
}

class Class1 {
    newClass2() {
       return new Class2();
    }

    test() {
       console.log('testing class 1')
   }
}

const class1 = new Class1();
class1.test() //testing class 1
const class2 = class1.newClass2(); //new class 2
class2.test() //testing class 2

CodePudding user response:

If you are asking to have an object as the result of 2 merged objects this could be a solution:

const class1 = new Class1();
const class2 = new Class2();

let fusion= {
    ...class1 ,
    ...class2 
};

So for example:

let a = {name : 'John'};
let b = {surname : 'Doe'};

let fusion = {...a,...b}; //will be {name: 'John', surname: 'Doe'}

That solution uses the spread operator:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

If you meant something else please correct me.

But on the other hand if you really wanted to instantiate Class2 using the constructor belonging to Class1, you could do something very very shady like this:

Class2.constructor = Class1.constructor;
let obj = new Class2();

But you are assigning a new constructor to Class2 using a function belonging to Class1 and the result will be very dirty unless you know in advance what you are doing. But that's exactly what you asked for.

I'd like to mention the fact that this way Class1 and Class2 don't need to know each other in advance and the dependency to each of them is made in the caller domain.

CodePudding user response:

Yes. You could, for instance, do it like this, using a class expression and a getter that fetches, in this case, a static property of Class1

class Class1 {
    get Class2() {
        return Class1.c2;
    }
}
Class1.c2 = class {
    constructor(foo) { }
};
var c1 = new Class1();
var c2 = new c1.Class2(42);
  • Related