Created
April 22, 2021 18:21
-
-
Save senthilp/8ef9e0dabaed7d3fe391609c13581c06 to your computer and use it in GitHub Desktop.
lazy-loading property pattern for classes
This file contains hidden or 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
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