In Javascript we can'not directly next class within class but way to do it is as follows
Using static keyword
class OuterClass {
constructor() {
this.outerProperty = 'Hello from outer class';
this.innerClass = new OuterClass.InnerClass();
}
outerMethod() {
console.log(this.outerProperty);
this.innerClass.innerMethod();
}
static InnerClass = class {
constructor() {
this.innerProperty = 'Hello from inner class';
}
innerMethod() {
console.log(this.innerProperty);
}
}
}
const outerObj = new OuterClass();
outerObj.outerMethod(); // Output: "Hello from outer class" and "Hello from inner class"
Output:
Hello from outer class
Hello from inner class
Without static keyword
class OuterClass {
constructor() {
this.outerProperty = 'Hello from outer class';
this.innerClass = new this.InnerClass()
}
outerMethod() {
console.log(this.outerProperty);
this.innerClass.innerMethod();
}
InnerClass = class {
constructor() {
this.innerProperty = 'Hello from inner class';
}
innerMethod() {
console.log(this.innerProperty);
}
}
}
const outerObj = new OuterClass();
outerObj.outerMethod(); // Output: "Hello from outer class" and "Hello from inner class"
Output:
Hello from outer class
Hello from inner class
No comments:
Post a Comment