Original text: making

Private property

Private properties are a very common feature in object-oriented programming (OOP) and generally meet the following characteristics:

  • Can it beclassInternal to different methods, but cannot be accessed outside the class;
  • Subclasses cannot inherit private attributes from their parent class.

Spare tire Class

Four years ago, in June 2015, ES6 was released as a standard. To mark this historic moment, the standard is also known as ES2015. At this point, classes in JavaScript were converted from back-up. Until now, class had been the JS keyword, hidden away. Class is considered a syntactic sugar of JS, which brings to JavaScript the ability to describe an entity in object-oriented terms. However, it seems that this is not enough. The capabilities of class are far from what JS developers expect. So the big boys at TC39 are trying to do better, too, and have come up with a new proposal:

class Foo { #a; Constructor (a, b) {this.#a = a; this.b = b } }Copy the code

The above private attribute declaration needs to be compiled by a compiler such as Babel before it can be used properly.

The proposal has reached Stage 3 and the future is up!

However, the JSer can’t wait……

JSer struggle

Through certain encapsulation of data, JS developers embarked on the curve to achieve “private attribute” road.

1. It’s a convention

The JS world prefixed a variable with the underscore “_” as an unwritten convention that it is a private property; But in reality, it remains a public property as if it were wearing an emperor’s new clothes.

2. The closure

Local variables are defined in the constructor scope and exposed externally via closures.

3. Symbols & Getters

Using the Symbol variable as an object key, we can simulate more realistic private properties.

getOwnPropertySymbols
Symbol

4. WeakMap & Getters

WeakMap is implemented in the same way as Symbol.

Shoulders of giants

Above, is the current stage of JS attribute private more feasible scheme, may be rarely used in practice, but if you encounter this problem in the interview, perhaps these schemes can be referred to.

However, in all of these scenarios, it is recommended to choose TypeScript private.

Finally, readers are welcome to comment and share your views on implementing private properties in JS


With reference to:

  • ECMAScript Classes – Keeping Things Private