Red Huang

Red Huang

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

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

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

Private properties of classes can now be represented using the # symbol.

Now#

If a class wants to use private properties, it must implement them using Symbol, WeakMap, or other methods.

 var _action = Symbol('action');

class Person {

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

Future#

And now, after the update, we can directly use the example code.

 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 documentation also provides some key points:

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

Of course, the community has raised some concerns:

  1. In many languages, # represents comments, so will it cause confusion?
  2. TypeScript has secretly implemented private fields, 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 major impact on the ES ecosystem. Writing JavaScript is now like writing CSS, even the # symbol 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.