RixTheTyrunt
RixTheTyrunt

Reputation: 405

How to make a class in a another class in JavaScript?

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?

Upvotes: 1

Views: 1603

Answers (2)

kacper destruktor
kacper destruktor

Reputation: 26

You can try sth like this;

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

You can also use static

Upvotes: 0

Ahmad Habib
Ahmad Habib

Reputation: 2382

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
    }
};

Upvotes: 2

Related Questions