Here’s the simplest way to create dependency injection in plain JavaScript. (The correct way. Not the convoluted and overblown Engine/Pistons/Car sample all over the Internet.)

function Parent() { } //simple class

function Kid(mother, father) {
   if( !(mother instanceof Parent) )
      throw new Error("Kid requires an instance of 'Parent' for their mother.");

   if( !(father instanceof Parent) )
      throw new Error("Kid requires an instance of 'Parent' for their father.");

   this.Mother = mother;
   this.Father = father;

let joey = new Kid(); //error thrown here

//every kid has two parents...
let mary = new Parent(); //mom
let john = new Parent(); //dad
let nicole = new Kid(mary, john);

Yes, seriously, it’s that simple. And it’s done the correct way, because proper Dependency Injection requires the creation of the instance of the classes to be passed to the constructor (or setter methods).

The D.I. happens at the point of detecting of mother / father are instances of Parent. If one of them is not, then an error is thrown. That error prevents the object from being created – thus, actual dependency.

It does not create the objects for you… otherwise, it’s not injection. It’s just “creating the objects for you.” Because, if the object was created within the class for you, it becomes attached to that class… it’s not injection if it exists already within you.

That would be called projection, a process of an object creating other objects just above its scope… which is outright dangerous.

JavaScript doesn’t have an inherit way of detecting, in parameters, if an object is an instance of that class. Though, hopefully, this changes as ES2019 and beyond becomes more capable. However, this example is in plain JavaScript, which doesn’t have those features.