1

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?

2 Answers 2

2

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
    }
};
Sign up to request clarification or add additional context in comments.

4 Comments

And the usage??
parent = new Parent; new parent.Child;
How to add a function inside that new Parent.Child()?
I can't use js class bla { static FooBarBaz = class { function poof() { console.log("Poof!") } } };
0

You can try sth like this;

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

You can also use static

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.