Skip to content

Instantly share code, notes, and snippets.

@dmwyatt
Created February 11, 2021 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmwyatt/e5f0791929085b3c8e510e93ed3d1095 to your computer and use it in GitHub Desktop.
Save dmwyatt/e5f0791929085b3c8e510e93ed3d1095 to your computer and use it in GitHub Desktop.
[lazyProperty] Lazy getters on JS classes.
**
* Lazily-evaluated getters.
*
* ```js
* class Person {
* get name() {
* lazyProperty(this, 'name', calculateSomeValueForName())
* return this.name
* }
* }
* ```
*
* @param {any} context - `this` from the class.
* @param {string} propertyName - The name of the property on the class.
* @param {any} value - The value to cache.
*/
export function lazyProperty(context, propertyName, value) {
Object.defineProperty(context, propertyName, {
value,
writable: false,
configurable: true,
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment