Example of Inner Classes in Typescript
(available since 1.6)
The implementation method is actually "class expressions".
We use them to create a private "inner class" (e.g. myClassExpresion) which is instantiated with the parent class's this and assigned to a public property of the parent class (e.g. innerClassInstance).
Unfortunately, the "inner class" does not have access to private or protected members of the parent.
Unfortunately, the "inner class" does not have access to private or protected members of the parent.
class Greeter { constructor(message: string) { this.greeting = message; } //inner class definition private myClassExpresion = class { constructor(private parent: Greeter){} public say(x: number) { return this.parent.greet() + " " + x; } } public greet() { return "Hello, " + this.greeting; } // inner class instance public innerClassInstance = new this.myClassExpresion(this); private greeting: string; } // USAGE let greeter = new Greeter("I am number"); alert(greeter.innerClassInstance.say(9));
note: the inner class must be defined within the parent class before it is instantiated.
No comments:
Post a Comment