Search code examples
javascriptclassinstance

How to call a function from class where instance of another class


I'd like to ask you if there is another way to call function from a class where this INSTANCE of another class is coming from?

Or do you think my approach is correct?

class App(){
  constructor(){
    this.interface = new Interface();
  }

  refresh(){
  ...refresh app somehow...   
  }
}

class Interface(){
  constructor(){}

  changeInterface(){
    ...change interface somehow...
    this.App.Refresh(); // => I need to call this function from previous class
  }
}

var myGlobalVariable = new App();
    myGlobalVariable.interface.changeInterface();

Only I can think of is to use global variable inside...but than I need to set this variable and use it all the time

var myGlobalVariable = new App();
    myGlobalVariable.interface.changeInterface();

and use it in a Class

class Interface(){
  constructor(){}

  changeInterface(){
    ...change interface...
    myGlobalVariable.App.Refresh(); // => call function from pre set
  }
}

Or maybe my thinking is wrong and I have to change it?

Thanks.


Solution

  • as VLAZ mentioned I had to create another link with "this" and then use it in constructor so...

    class App(){
      constructor(){
        this.interface = new Interface(this); // using this inside of new instance
      }
    
      refresh(){
      ...refresh app somehow...   
      }
    }
    
    class Interface(){
      constructor(thisValue){
        this.App = thisValue; // pas "thisValue" to local variable
      }
    
      changeInterface(){
        ...change interface somehow...
        this.App.Refresh(); // => calling this function from previous class using this.App variable in constructor
      }
    }
    

    BIG BIG thanks @VLAZ!