问题
Would it be a bad idea to pass anything that could possibly not work in the future to a class?
For instance, passing a database connection (or anything that can possibly have it's methods rendered useless) to multiple classes? With JavaScript, these are passed by reference, therefore if the database connection is canceled outside of the class, the object within the classes wouldn't work? Now would this be bad, seeing now that all the models and things which use the database in methods will not work (without any notice that all the classes using the object now cannot be used).
回答1:
A database connection is a perfect example of something to pass into a class for dependency injection.
Dependency injection is useful for testing your models/classes, and during testing you want to "mock" certain services such as your database. In your tests, instead of "injecting" a database object, you would "inject" a mock object that models your database functionality.
来源:https://stackoverflow.com/questions/24252904/dependency-injections-with-mutable-objects