I have this situation in JS:
class Outer{
constructor() {
this.fruit = "orange";
let inner = new this.Inner();
}
Inner = class{
constructor() {
// here
}
}
}
let outer = new Outer();
From the constructor of the class Inner
, how can I get the current instance of Outer, as if this
was used in the outer constructor?
Sure, I could pass the outer class as a parameter into the inner class' constructor, or put the outer class in a variable, but is there any other method?
You can use an IIFE to create the class and give it the current instance:
class Outer{
constructor() {
this.fruit = "orange";
let inner = new this.Inner();
}
Inner = (instance => class{
constructor() {
console.log(instance instanceof Outer);
console.log(instance.fruit);
}
})(this)
}
let outer = new Outer();
However, a more idiomatic approach is to accept the instance in the constructor of Inner
. Then the class can be separated from Outer
and Outer
can expose a method that handles the construction of Inner
which can create many instances of it:
class Inner {
constructor(instance) {
console.log(instance instanceof Outer);
console.log(instance.fruit);
}
}
class Outer{
constructor() {
this.fruit = "orange";
let inner = this.makeInner();
}
makeInner() {
return new Inner(this);
}
}
let outer = new Outer();
const secondInnerInstance = outer.makeInner();
Or alternatively consider breaking the circular dependency between the two and introducing a factory to handle the more complex construction.