Skip to content
Advertisement

How do I access an instance variable of an outer class from within an inner class?

Let’s say I have the following code:

class Cookie{
    ChocolateChip = class{
        constructor(){
            
        }
        sayMyOuterClassName(){
            console.log(???);
        }
    }
    constructor(name){
        this.name = name;
        this.someInstance = new this.ChocolateChip();
        this.someInstance.sayMyOuterClassName();
    }
}

let aCookie = new Cookie("Bob");

What do I replace ??? with in order to make it print out "Bob"? I saw someone suggest Cookie.this.name, but I’m afraid to try that without knowing all the implications of it, since I need to rely on the code I’m writing right now, and if it breaks in the future I don’t want it to be because I used this line of code that I don’t fully understand and end up wasting loads of time.

Aside from this question, I also want to ask… I was previously declaring my classes as static and using them like new OuterClassName.InnerClassName(), but I switched because I assumed that would prevent me from accessing instance variables from my outer class inside the inner classes… Is that correct? Does declaring an inner class as static prevent it from accessing its outer class’ variables?

Advertisement

Answer

Add a reference to the parent:

class Cookie{
    ChocolateChip = class {
        constructor(parent){
            this.parent = parent;
        }
        sayMyOuterClassName(){
            console.log(this.parent.name);
        }
    }
    constructor(name){
        this.name = name;
        this.someInstance = new this.ChocolateChip(this);
        this.someInstance.sayMyOuterClassName();
    }
}

let aCookie = new Cookie("Bob");
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement