I need to lazy load some class instance variables in JavaScript. Taking inspiration from Any way to define getters for lazy variables in Javascript arrays? and from Self-references in object literal declarations I have tried this solution


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

See here for a proof of concept.