Skip to content

Instantly share code, notes, and snippets.

@tetsuharuohzeki
Created June 2, 2012 01:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tetsuharuohzeki/2856054 to your computer and use it in GitHub Desktop.
Save tetsuharuohzeki/2856054 to your computer and use it in GitHub Desktop.
ES5 lazy getter function
function lazyGetter(aObject, aName, aLambda) {
Object.defineProperty(aObject, aName, {
get: function () {
delete aObject[aName];
return aObject[aName] = aLambda.apply(aObject);
},
configurable: true,
enumerable : true,
});
}
lazyGetter(this, "bar", function () {
return 1;
});
console.log(this.bar);// 1
this.bar++;
console.log(this.bar);// 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment