Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: protected and private constructors #7

Open
trusktr opened this issue Nov 29, 2018 · 0 comments
Open

feature: protected and private constructors #7

trusktr opened this issue Nov 29, 2018 · 0 comments

Comments

@trusktr
Copy link
Owner

trusktr commented Nov 29, 2018

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 prototype property from the constructor (when using the Class({}) form, as using the wrapped class form yield an unmodifiable prototype).
    • Trying to extend from it with class will result in Uncaught TypeError: Class extends value does not have valid prototype property undefined
    • But then class instances will not have public props/methods if we call new on 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.
  • constructors are always synchronous, so maybe we can rely on a sync call stack variables:
    • The class extends statement would not fail, but because the class is marked as private, as soon as the constructor is called lowclass can throw an error like TypeError: the class 'ClassMadeWithLowclassWhichHasPrivateConstructor' has a private constructor and can not be extended from when it detects that the new call 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant