lowclass
lowclass copied to clipboard
feature: protected and private constructors
Make a feature similar to protected constructor() {} and private constructor() {} in TypeScript.
Maybe it isn't completely possible. For example, how do we prevent someone from doing class Foo extends ClassMadeWithLowclassWhichHasPrivateConstructor {}?
We can definitely prevent that if the extending author uses the form Class('Foo').extends(ClassMadeWithLowclassWhichHasPrivateConstructor, {}).
But as for native class extension what can we do? Some ideas:
- Maybe we can delete the
prototypeproperty from the constructor (when using theClass({})form, as using the wrappedclassform yield an unmodifiable prototype).- Trying to extend from it with
classwill result inUncaught TypeError: Class extends value does not have valid prototype property undefined - But then class instances will not have public props/methods if we call
newon the constructor because the prototype is missing. We'd need to provide a helper for constructing classes inside the code of the class definition, where the helper would restore the prototype (gets it from private scope in lowclass) and then constructs an instance, then removes the prototype.
- Trying to extend from it with
- constructors are always synchronous, so maybe we can rely on a sync call stack variables:
- The
class extendsstatement would not fail, but because the class is marked as private, as soon as the constructor is called lowclass can throw an error likeTypeError: the class 'ClassMadeWithLowclassWhichHasPrivateConstructor' has a private constructor and can not be extended fromwhen it detects that thenewcall is not inside the scope of the class that owns the constructor - similarly for
protected, lowclass can keep track of variables in the constructor call stack. As soon as a constructor (from a subclass) is called, a variable is set (f.e.allowConstruction) so that when the protected super constructor is eventually called it will not throw. After construction is complete, the variable is set back to false. Calling the constructor in public code will therefore throw.
- The