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?
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?
Share Improve this question edited 16 hours ago VLAZ 29.1k9 gold badges62 silver badges84 bronze badges asked 17 hours ago AnpangAnpang 131 silver badge3 bronze badges New contributor Anpang is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. 17 | Show 12 more comments1 Answer
Reset to default 1You 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.
new outer.Inner(outer);
, I have to putouter
twice. Sometimes it's just a variable name, but sometimes it's a long expression, so I personally don't consider that as clean. – Anpang Commented 17 hours agoOuter
. It's accessible. If you want to access the instance, you have to pass it as argument. TBH, I don't even see what you criticize here. You were asked for clarification and got your answer. What exact statement is a problem? – jabaa Commented 16 hours ago