JavaScript类

时间:2016-05-12 12:40:32

标签: javascript lazy-loading lazy-initialization

我需要JavaScript中的延迟加载变量。从中获取灵感 Any way to define getters for lazy variables in Javascript arrays?Self-references in object literal declarations 我试过这个解决方案



var console = {
  log: function(s) {
    s = s.replace(/\\n/, '<br/>');
    document.getElementById("console").innerHTML += s + "<br/>"
  }
}

function MyClass() {
  this.LazyProperty = {
    _loaded: false,
    _autoload: function() {
      console.log("MyClassLazyProperty-1 " + JSON.stringify(this));
      if (this._loaded) {
        console.log("MyClass.LazyProperty-2 " + JSON.stringify(this));
        return this;
      } else {
        setTimeout(function(self) {
          self._loaded = true;
          self.profile = {
            displayName: "Loreto Parisi"
          };
          console.log("MyClass.LazyProperty-3 " + JSON.stringify(self));
          self._autoload();
        }, 300, this);
      }
    }
  }._autoload()
  this.User = {
    username: "loretoparisi",
    _autoload: function() {
      console.log("MyClass.User-1" + JSON.stringify(this));
      return this;
    }

  }._autoload()
}

var c = new MyClass();

console.log("c.User\n" + JSON.stringify(c.User));
console.log("c.LazyProperty\n" + JSON.stringify(c.LazyProperty));
&#13;
<div id="console" />
&#13;
&#13;
&#13;

代码说明 假设我想通过异步查找(如休息请求)的结果填充延迟属性,我需要在第一次查找时保持加载状态。 _autoload函数进行异步查找并设置响应属性,因此我希望在此填充对象:

c.LazyProperty

,结果为undefined。为什么呢?

修改 我发现在调用setTimeout时会发生某些事情,因此this的引用会丢失,所以我添加了一个defer函数来保留它:

_defer : function() { this._autoload(); return this },

此时延迟加载器将正常工作:

&#13;
&#13;
var console = {
  log: function(s) {
    s = s.replace(/\\n/, '<br/>');
    document.getElementById("console").innerHTML += s + "<br/>"
  }
}

function MyClass() {
  this.LazyProperty = {
_loaded: false,
_defer : function() { if(!this._loaded) this._autoload(); return this },
_autoload: function() {
  console.log("MyClassLazyProperty-1 " + JSON.stringify(this));
  setTimeout(function(self) {
      self._loaded = true;
      self.profile = {
        displayName: "Loreto Parisi"
      };
      console.log("MyClass.LazyProperty-3 " + JSON.stringify(self));
    }, 300, this);
}
  }. _defer()
  this.User = {
username: "loretoparisi",
_autoload: function() {
  console.log("MyClass.User-1" + JSON.stringify(this));
  return this;
}

  }._autoload()
}

var c = new MyClass();

console.log("c.User\n" + JSON.stringify(c.User));
console.log("BEFORE: c.LazyProperty\n" + JSON.stringify(c.LazyProperty));
setTimeout( function() {
   console.log("AFTER: c.LazyProperty\n" + JSON.stringify(c.LazyProperty));
},1000);
&#13;
<div id="console" />
&#13;
&#13;
&#13;

鉴于此解决方案,在第一次执行中,我不知道该属性在分配后为undefined的原因。

0 个答案:

没有答案