Created
February 11, 2021 18:51
-
-
Save dmwyatt/e5f0791929085b3c8e510e93ed3d1095 to your computer and use it in GitHub Desktop.
[lazyProperty] Lazy getters on JS classes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
** | |
* 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