美文网首页实用前端
es 6 类定义静态方法 静态常量 私有成员

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

作者: proud2008 | 来源:发表于2016-12-14 11:05 被阅读215次

静态方法

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

相关文章

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

    静态方法 静态常量 只定义get方法不定义 set,有static set 则可修改了 私有成员 使用WeakMa...

  • 1、类的定义 类的成员出现顺序:公共静态常量、私有静态变量、私有实体变量,然后才是公共函数,私有的工具函数紧随在该...

  • es6 class实现静态属性、私有属性、方法

    1.class实现静态属性 参考:ES6 class 静态属性和私有方法 es6中实现了静态方法,但是没有静态属性...

  • 深入es6之class

    es5定义一个类 es6定义一个类 es6原型方法(内部this是实例化的类) 静态方法(内部this是类) 继承

  • 7.6 类的静态成员

    7.6 类的静态成员 静态成员的特性 静态成员属于类,而不是对象。 类型可以是类对象、指针、引用、常量等。 静态成...

  • 静态属性

    静态属性就是被 类 调用的属性 叫做静态属性 ES5 静态属性写法类.方法 = function() {} ES6...

  • python 进阶 面向对象(三)

    成员修饰符:公有、私有普通字段、静态字段、普通方法、静态方法、类方法、普通特性class Foo: xo ...

  • Kotlin 静态类,静态方法

    整个静态类: 类中的部分静态方法 全局静态直接新建一个 Kotlin file 然后定义一些常量,方法 补充:我们...

  • TypeScript中的关键字static

    TypeScript中的关键字static ES6中的静态成员在TypeScript也存在,类的静态成员可以使用类...

  • javascript中ES6的class写法

    在ES6中,javascript实现类定义、类继承及类中定义变量,构造方法,一般方法,静态方法 代码中均有注释

网友评论

    本文标题:es 6 类定义静态方法 静态常量 私有成员

    本文链接:https://www.haomeiwen.com/subject/cydimttx.html