【问题标题】:Expose and use privileged method in object after initialization初始化后在对象中公开和使用特权方法
【发布时间】:2019-09-10 02:54:39
【问题描述】:

我有两个对象构造函数“类”。第一个运行异步操作并在数据准备好时执行回调。在回调中,我初始化了第二个函数。

我希望能够通过包装函数公开某些属性。这些属性将根据需要每隔一段时间进行轮询。我不确定在查询这些属性时,第二个对象是否已经初始化。

var Wrapper = function(){
   //This may take a while to finish
   var foo = new Foo(function(err,data){
      bar = new Bar(data);
   });

   //this can be queried every few 100ms
   this.getProp(){
       return this.bar.getProp();
   }
}

var w = new Wrapper();
w.getProp(); //Cannot read property 'getProp' of undefined

公开此类数据的最佳方式是什么?

【问题讨论】:

  • 使用new关键字初始化对象。
  • 这似乎不是问题。问题是在创建一个新的 Wrapper 时,bar 还没有被初始化。
  • Foo类什么时候调用提供的回调函数?
  • 在代码中,提供给 Foo 的函数永远不会被调用,有时可能会被 Foo 调用,但不确定何时发生。由于代码的异步特性,条形图也可能未定义。在这种情况下,您究竟希望发生什么?您要等待数据吗?如果是,bar 属性必须是我们可以等待的承诺

标签: javascript function oop


【解决方案1】:

我不会说这是最好的方法。这更像是一个让你的伪代码工作的例子。

function Foo(cb) {
  // simulate initialization delay
  setTimeout(() => cb(null, {
    wookies: 12
  }), 3000);
}

function Bar(data) {
  this.data = data;
}

function Wrapper() {
  const setBar = (err, data) => this.bar = new Bar(data);
  //This may take a while to finish
  new Foo(setBar);

  //this can be queried every few 100ms
  this.getProp = function() {
    if (!this.bar) {
      // not ready yet
      console.log('still awaiting initialization');
      return;
    }
    return this.bar.data;
  }
}

const w = new Wrapper();

function go() {
  const x = w.getProp();
  if (!x) {
    setTimeout(go, 100);
  } else {
    console.log(x);
  }
}

go();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    相关资源
    最近更新 更多