Home > Blockchain >  How to make a class in a another class in JavaScript?
How to make a class in a another class in JavaScript?

Time:12-03

I want to make something like bla.FooBarBaz in JavaScript, but, bla is a class and FooBarBaz is a class, but INSIDE THE bla CLASS. How to do it?

CodePudding user response:

There are no nested classes in ES6 but yes, you can put a second class as a static property on another class, like this:

class Parent {
    //code
}
Parent.B = class {
   //code
};

or by using extra scope:

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

But with the help of this proposed class, you can write a single expression or declaration:

class Parent {
    //code
    static Child = class {
         //code
    }
};

CodePudding user response:

You can try sth like this;

class bla {
   constructor() {
     this.FooBarBaz = new FooBarBaz();
   }
}

You can also use static

  • Related