JSFiddle - React, Tailwind, and code Playground

by Pankaj Kargirwar

JavaScript

class MainClass {
  constructor() {
    this.property = 'value';
    this.subclassInstance = new SubClass(); // Instantiate the subclass
  }

  mainMethod() {
    console.log('Main method called');
  }
}

class SubClass {
  constructor() {
    // No need to pass the main class context here
  }

  subclassMethod = () => { // Use arrow function to retain the 'this' context
    console.log(this.property); // Access property of the main class
    this.mainMethod(); // Call method of the main class
  }
}

const instance = new MainClass();
instance.subclassInstance.subclassMethod(); // This will access properties and methods of the main class