0

In JavaScript, it's possible to assign a ES6 class to a variable (MDN: Class Expression):

const Foo = class {
  constructor() {}
  bar() {
    return "Hello World!";
  }
};

So, say I have a class called Animal that looks like this:

class Animal {
  // Properties and methods for the `Animal` class...
}

Then assigned a class to a static property, like this:

class Animal {
  // Properties and methods for the `Animal` class...
  static Human = class {
    // Properties and methods for the `Animal.Human` class...
  };
}

For example, to use like this:

const alex = new Animal.Human();

This is not something I've seen done in practice, so would this be bad practice?

Malekai
  • 4,765
  • 5
  • 25
  • 60
  • 1
    This is basically using the class as a module. While you can do this, JS has a real module system now. – Barmar Jun 19 '23 at 17:37
  • 1
    I see no usecase to assign a class to a variable. Also I see no usecase to nest classes. Even if it is possible it makes it really complicated to understand the code – Thallius Jun 19 '23 at 17:42

1 Answers1

1

No, this is the standard syntactical pattern for nested classes, and has been in use for years.

However, it is rather unusual to nest classes in modern javascript - not really because it's a bad practice, but rather because it's simply not necessary. It was more common when libraries were using the module pattern and exposed namespace objects (e.g. as IIFE return values, global variable, or CommonJS module exports), sometimes these namespace objects were classes (or at least functions) themselves and had others as object member properties. But now, people just use ES modules, and provide separate modules for separate classes, with hierarchical module identifiers at best.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375