...

/

Solution: Lazy-Load a Heavy Service Only When First Used

Solution: Lazy-Load a Heavy Service Only When First Used

Use the get trap to instantiate a service only when it’s first accessed.

We'll cover the following...

Solution explanation

  • Lines 2–10: We define the DataService class to simulate an expensive dependency.

    • Its constructor logs a message when initialized, representing heavy setup work.

    • The fetchData() method represents an operation that other modules will eventually call.

  • Lines 13–26: The createLazyService() function builds the Proxy responsible for lazy initialization.

    • A variable instance holds the actual DataService instance, starting as null.

    • The ...