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
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
}
};
4 Comments
John GradientOS
And the usage??
Ahmad Habib
parent = new Parent; new parent.Child;
John GradientOS
How to add a function inside that
new Parent.Child()?John GradientOS
I can't use
js class bla { static FooBarBaz = class { function poof() { console.log("Poof!") } } }; You can try sth like this;
class bla {
constructor() {
this.FooBarBaz = new FooBarBaz();
}
}
You can also use static
1 Comment
Community
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.