javaScrip

class中使用Generator异步调用

const bar = Symbol('bar');
const snaf = Symbol('snaf');
export default class beforChat {
  #x;
  #config = {
    url: 'baidu',
    time: 3000,
    ping: () => ({})
  };

  url = '';

  /**
   * 静态方法
   */
  static myStaticProp = 42;

  constructor(url) {
    this.#config.url = url;
    this.init();
  }

  init() {
    console.log(this.#config, '=====');
  }

  /** static 静态的私有属性或私有方法。
   * 只能在底部使用类调用 console.log(myClass.myStaticProp,'pi')
   */
  static random() {
    console.log('I heard you like random numbers…');
  }

  /**
   * Generator异步调用 相当于下面
    step1(function (value1) {
        step2(value1, function(value2) {
            step3(value2, function(value3) {
              step4(value3, function(value4) {
                // Do something with value4
              });
            });
      });
    });
   */
  *helloWorldGenerator() {
    try {
      yield console.log('hello');
      yield this.errFun(); //捕获错误后停止往下执行
      yield console.log('3');
      yield console.log('end');
    } catch (e) {
      console.log(e, '捕获异常');
    }
  }

  /**
   * 外部调用Generator
   */
  objectEntries() {
    const hw = this.helloWorldGenerator();
    for (const i of hw) {
    }
  }

  /**
   * 错误方法
   */
  errFun() {
    throw new Error('a');
  }

  use(obj) {
    if (this.#testPrivate in obj) {
      // 私有属性 #foo 存在
    } else {
      // 私有属性 #foo 不存在
    }
  }

  // 公有方法,全局可用
  foo() {
    // console.log(this.#x)  // 1
    // console.log(this[bar](snaf))  // 33
    // console.log(this.PI,'uu') //undefined
  }

  // 私有方法
  [bar](snaf) {
    return 33;
  }
}

console.log(myClass.myStaticProp, 'pi'); //42

// ## 页面调用
// let beforChat = new BeforChat()
// beforChat.objectEntries()
上次更新: