Dependency Injection is a fairly complex topic for beginners. It might not be necessary to know the concept but knowing it will help you make bette...
For further actions, you may consider blocking this person and/or reporting abuse
What you describe is not dependency injection, but dependency inversion. You made it so the class Pet does not automatically create a dependency, but rather takes it as a parameter. I think an important bit that you left out is the fact that the instance of the Dog class(fluffy) can be reused in other classes. Good point to specify a purpose for dependency inversion is to create more instances of the dependant class with different dependencies. The bit about the injector is right, dependency injection is a pattern where you don't even need to create any of your services / components / dependencies, but rather let a framework create them for you and figure out the order of the creation and injection of the dependencies. I wish you detailed more on that part.
My aim was to make people understand the concept of loose coupling through dependency injection. This is a beginner focused post and don't want to confuse people with information they might not need. Thanks for reading.
Without being an expert I think that dependency injection is one form of practical application of the dependency inversion.
right, agree
I agree with the Author. Js is highly dynamic and powerful so I think it does not really need any kind of IOC. If I pick up the example I will probably end up with something like this:
function whatDoesMyPetSay < T extends { speak: () => string; }>(pet: T): string {
pet.speak();
}
🙂
Yes, I agree, You can do it in many ways in JavaScript.
many thanks. I've read about
"Dependency inversion principle"
and I know it clearly after reading your article.Even though JS doesn't have interface, this is a good, clear and simple example.
in JS files, I usually use
export and import
some functions into a module, so is it the way could replace DI?Yes, you dont really need to create class objects to use funtions in js. You can directly use functions in most of the case. Glad you liked it.
JavaScript also happens to be dynamic in nature.
Great
Thanks for reading.
Good read
Thanks for reading
Dependency injection is passing dependencies as parameters, js supports higher-order functions, so why just don't use partial application and pass functions as dependencies to other functions?
Yes, that will indeed be the most optimal way in javascript or any other functional programming language. But DI is very Object oriented concept. If you are working with Class Objects you might be need to use DI. Its all based on situation of use.
Very nice and easy explanation of not so easy concept. Thanks 👍🏻
Thanks, glad you liked it :)