[ES7] Private, Static class Members

Morden Javascript allows us to write private and static class memebers.

 

To do this, we need to install babel plugins:

[ES7] Private, Static class Members 

 

First, let see "static member":

class Cart {
  static name = "My Cart";
  
}

console.log(Cart.name)

This is enabled by @babel/plugin-proposal-class-properties.

 

Then let's see private method:

class Cart {
  static name = "My Cart";
  #items;
  constructor(items = []) {
    this.#items = Object.freeze(items);
  }
  add(item) {
    const state = [...this.#items, item];
    this.#items = Object.freeze(state);
  }
  remove(id) {
    const state = this.#items.filter(item => item.id !== id);
    this.#items = Object.freeze(state);
  }
}

By adding "#" sign to the variable, we can convert this variable to a private prop.

If you console log "new Cart()" you won't see "#items".

 

上一篇:es7.+(一)检索


下一篇:ES7 语法使用小记 Elasticsearch