This lesson is only accessible in the paid version of the course.
Get access to all lessons 💫 price: 34.99$
Do you speak JavaScript?
In this video, we will discuss dependency injection in JavaScript and how it can be used to decouple the dependencies of an object from its implementation. We will learn about the benefits of dependency injection, such as improved testability and flexibility, and explore how to implement it in your own code.
Dependency injection is a technique in software development that allows you to decouple the implementation of a module from its dependencies. This means that a module does not need to know how to create its own dependencies, but instead they are passed to it when it is created or called. This allows for greater flexibility and reusability of code, as well as making it easier to test.
Here is an example of dependency injection in JavaScript:
class User {
constructor(db) {
this.db = db;
}
getUsername(id) {
return this.db.query(`SELECT username FROM users WHERE id = ${id}`);
}
}
const mySql = new MySql();
const user = new User(mySql);
console.log(user.getUsername(1));
In this example, the User
class has a dependency on a db
object. Instead of creating the db
object inside the User
class, it is passed to it when it is created. This allows the User
class to be reused with different implementations of the db
object, such as a different database or a mock object for testing.
Practice is the fastest way to learn knowledge permanently. I have prepared a small task for you related to the lesson.
Materials related to the lesson:
→ Files associated with the lesson