Skip to content

JavaScript nested classes

  • by

There are no nested classes in JavaScript (ES6). You can put a second class as a static property on another class, like this:

class A {
    …
}
A.B = class {
    …
};

or you use an extra scope:

var C;
{
    class D {
        constructor() { }
    }
    C = class C {
        constructor() { }
        method() {
            var a = new D();  // works fine
        }
    }
}

With the proposed class field syntax, it will also be possible to write a single expression or declaration:

class A {
    …
    static B = class {
         …
    }
};

Source: stackoverflow.com/

This concept allows you to encapsulate related functionality and data within a parent class. Nested classes are not a separate language feature but are implemented by defining a class as a property of another class.

JavaScript nested classes

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    class A {
      constructor () {
        this.B = class {
          echo () {
            console.log('I am B Nested class');
          }
        }
      }
      echo () {
        this.b = new this.B;
        this.b.echo();
      }
    }

    var a = new A;

    a.echo();
  </script>
</body>
</html> 

Output:

JavaScript nested classes

Do comment if you have any doubts or suggestions on this Js nested class.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *