Closed jithujoshyjy closed 4 years ago
This proposal continues from the class fields proposal, which introduces the #
sigil for private names. There’s a Syntax FAQ there which may help clarify the parameters that need to be satisfied by any solution.
Your example code uses this.private
, which already is valid JS with a different and incompatible meaning (a member expression referencing a property with the key "private").
The properties/methods with the inherent keyword are private but can be inherited by child classes.
A private name’s privateness is achieved by being a name that is declared and exists within a specific scope. Just as you can’t introspect variables within a closure just because you have a reference to a function, you also can’t access the private names of a class because you have access to a class — which is all a subclass in JS is; there are no privileges re: what code can and cannot extend a given class.
There are follow-on proposals that investigate private names that aren’t bound to class bodies specifically, but to associate “does inherit” with the declaration of the name, rather than achieving it via explicit/narrow sharing at the point where it’s to be consumed, is not compatible with private members actually being private.
well it's just a suggestion. Any way, thanks for the wise reply.
The # sign used to mark a property/method as private seem a bit alien from the current syntax of JavaScript. This is just a humble suggestion for a new syntax:
class GreetWorld { constructor(word, world) { this.word = word; this.world = world; } sayGreeting() { return this.private.greeting; } private { greeting = this.word + " " + this.world; inherent greetWords = ["hello", "hai", "what's up"]; inherent showGreetWords() { return this.private.greetWords; } } } const greeter = new GreetWorld("What's Up", " Earth"); greeter.sayGreeting(); //What's Up Earth greeter.greeting //Error cannot read a private property
The properties/methods with the
inherent
keyword are private but can be inherited by child classes.