Red Huang

Red Huang

ECMA TC39 will implement the language feature of private in JavaScript.

This time, the ECMA TC39 Technical Committee has passed the draft of ECMAScript language features on Github.

For more details, you can check this https://github.com/tc39/proposal-class-fields

The private property of the class can be represented using #.

Now#

If a class wants to use private properties, it must be implemented using Symbol or WeakMap features or other methods.

 var _action = Symbol('action');

class Person {

   getXXX() {
      return this[_action]();
   }
   [_action]() {
      return 'hi';
   }
} 

Future#

And now, after the update, just steal the example and use it directly.

 class Counter extends HTMLElement {
  #xValue = 0;

  get #x() { return #xValue; }
  set #x(value) {
    this.#xValue = value; 
    window.requestAnimationFrame(this.#render.bind(this));
  }

  #clicked() {
    this.#x++;
  }

  constructor() {
    super();
    this.onclick = this.#clicked.bind(this);
  }

  connectedCallback() { this.#render(); }

  #render() {
    this.textContent = this.#x.toString();
  }
}
window.customElements.define('num-counter', Counter); 

The official also provided some key points.

  1. Better encapsulation.
  2. Private fields can only be declared at the field declaration and cannot be created later, but can be assigned values at any time like regular properties.

Of course, the community has raised some concerns.

  1. In many languages, # represents comments, will this cause confusion?
  2. TypeScript secretly implemented private, and now the syntax is different, causing cognitive burden.

Now, Babel 7.0+ is planning to implement it https://github.com/babel/babel/pull/8654

This change seems to have a big impact on the ES ecosystem again. Writing JS is like writing CSS, even # is involved. But since everyone is on this train, we can only hold on tight.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.