JS Getter Lazy Init Pattern

In a recent comment on one of my patches, Mark made what I thought was a clever suggestion for how to do lazy initialization of a value via a js getter:

>+ /// The user's profile dir, which we'll cache and use a lot for path clean-up >+ _profileDir: null, >+ >+ /// Spotlight won't index files in the profile dir, but will use ~/Library/Caches/Metadata >+ _getSearchPathForFolder: function spotlight_get_search_path(aFolder) >+ { >+ if (!this._profileDir) >+ this._profileDir = Cc["@mozilla.org/file/directory_service;1"] >+ .getService(Ci.nsIProperties) >+ .get("ProfD", Ci.nsIFile);

Why not store just the path of the profile directory?

Also, if you want to cache this value, but don't want to init it until first
use, you can do:

get _profileDir() {  
  delete this._profileDir;  
  return this._profileDir = Cc["@mozilla.org/file/directory_service;1"]  
                              .getService(Ci.nsIProperties)  
                              .get("ProfD", Ci.nsIFile);  
}

Probably something very common to others and I'm just seeing for the first time, but I like it!

Show Comments