Skip to content

Instantly share code, notes, and snippets.

@senthilp
Created April 22, 2021 18:21
Show Gist options
  • Save senthilp/8ef9e0dabaed7d3fe391609c13581c06 to your computer and use it in GitHub Desktop.
Save senthilp/8ef9e0dabaed7d3fe391609c13581c06 to your computer and use it in GitHub Desktop.
lazy-loading property pattern for classes
class MyClass {
constructor() {
const instance = this;
Object.defineProperty(this, "data", {
get() {
const actualData = "Something big...";
console.log(this === instance); // true
Object.defineProperty(instance, "data", {
value: actualData,
writable: false,
configurable: false
});
return actualData;
},
configurable: true,
enumerable: true
});
}
}
const object = new MyClass();
console.log(object.hasOwnProperty("data")); // true
const data = object.data;
console.log(object.hasOwnProperty("data")); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment