es 6 类定义静态方法 静态常量 私有成员

静态方法

class Foo {
  static classMethod() {
    return 'hello';
  }
}


静态常量

class Foo  {
  constructor() {
    super();
  }
  static get StaticData(){
    return "default"
  }
}

只定义get方法不定义 set,有static set 则可修改了

私有成员

let _counter = new WeakMap();
let _action = new WeakMap();

class Countdown {
  constructor(counter, action) {
    _counter.set(this, counter);
    _action.set(this, action);
  }
  dec() {
    let counter = _counter.get(this);
    if (counter < 1) return;
    counter--;
    _counter.set(this, counter);
    if (counter === 0) {
      _action.get(this)();
    }
  }
}

let c = new Countdown(2, () => console.log('DONE'));

c.dec()
c.dec()
// DONE

使用WeakMap

const _counter = Symbol('counter');
  const _action = Symbol('action');
  
  class Countdown {
      constructor(counter, action) {
          this[_counter] = counter;
          this[_action] = action;
      }
      dec() {
          if (this[_counter] < 1) return;
          this[_counter]--;
          if (this[_counter] === 0) {
              this[_action]();
          }
      }
  }
// properties whose keys are symbols:

http://www.2ality.com/2016/01/private-data-classes.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,273评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,874评论 18 399
  • Introduction to C++ (Season 1) Unit 1: Overview of C++ 第1...
    我是阿喵酱阅读 2,787评论 0 7
  • { "Unterminated string literal.": "未终止的字符串文本。", "Identifi...
    Elbert_Z阅读 10,923评论 0 2
  • 原本计划好的形成突然不能实施,有一种被堵的感觉,好想无所事事了
    倾黛阅读 164评论 0 0