JavaScript with Dependency Injection

Example app for illustrating DI

by Jeremy Likness

HTML

<div id="output">
</div>

JavaScript

function Main() {

	const output = document.getElementById("output");

	const log = msg => {
  	var p = document.createElement("p");
    p.innerText = msg;
    output.appendChild(p);
  };
  
  const $jsInject = new $$jsInject();
	
  function Car(wheels, engine) {
  	this.wheels = wheels;
    this.engine = engine;
    this.action = () => {
    	this.wheels.action();
      this.engine.action();
      log("The car drives by.");
    }
    log("Made a car.");
  }
  
  $jsInject.register("car", ["wheels", "engine", Car]);
  
  function Engine(pistons) {
  	this.pistons = pistons;
    this.action = () => {
    	this.pistons.action();
      log("The engine goes vroom vroom.");
    };
    log("Made an engine.");
  }
  
  $jsInject.register("engine", ["pistons", Engine]);
  $jsInject.register("testEngine", ["testPistons", Engine]);
  
  function Wheels() {
  	this.action = () => log("The wheels go 'round and 'round.");
    log("Made some wheels.");
  }
  
  $jsInject.register("wheels", [Wheels]);
  
  function Pistons() {
  	this.action = () => log("The pistons fire up and down.");
    log("Made some pistons.");
  }
  
  $jsInject.register("pistons", [Pistons]);
  
  function TestPistons() {
  	this.action = () => log("The test pistons do nothing.");
    log("Made some test pistons.");
  }
  
  $jsInject.register("testPistons", [TestPistons]);
  
  var car = $jsInject.get("car");
  car.action();
  var testEngine = $jsInject.get("testEngine");
  testEngine.action();
}

setTimeout(Main, 0);

"use strict";(function(e){function r(){this.container={}}function i(){var e=new r,t=this;this.get=e.get.bind(e);this.register=e.register.bind(e);e.container["$$jsInject"]=function(){return t}}var t=20,n=function(e){return Object.prototype.toString.call(e)==="[object Array]"};r.ERROR_RECURSION="Maximum recursion at ";r.ERROR_REGISTRATION="Already registered.";r.ERROR_ARRAY="Must pass array.";r.ERROR_FUNCTION="Must pass function to invoke.";r.ERROR_SERVICE="Service does not...