Search This Blog

2023/08/31

Dependency Injection using constructor

 // Service class that requires a dependency

class Service {
constructor(dependency) {
this.dependency = dependency;
}

doSomething() {
this.dependency.doAction();
}
}

// Dependency class
class Dependency {
doAction() {
console.log("Dependency is performing an action.");
}
}

// Creating instances and injecting dependencies
const dependency = new Dependency();
const service = new Service(dependency);

service.doSomething();

No comments:

Post a Comment