首页 > 解决方案 > 初始化后在对象中公开和使用特权方法

问题描述

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

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

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

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

标签: javascriptfunctionoop

解决方案


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

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();


推荐阅读