loading...

re: Dependency Injection in JavaScript 101 VIEW POST

FULL DISCUSSION
 

Hi Jeremy,
Thanks for your informative Article. by the way I re-wrote your code according to IoC and DI principles. Please let me know if my approach is correct or not.

// hidden setup JavaScript code goes in this preamble area function Wheels({ log }) { this.action = () => log("The wheels go 'round and 'round."); log("Made some wheels."); } function Pistons({ log }) { this.action = function () { log("The pistons fire up and down."); }; log("Made some pistons."); } function Engine({ log, pistons }) { this.pistons = pistons; this.action = function() { this.pistons.action(); log("The engine goes vroom vroom."); }; log("Made an engine."); } function Car({ wheels, engine, log }) { this.wheels = wheels; this.engine = engine; this.action = () => { this.wheels.action(); this.engine.action(); log("The car drives by."); }; log("Made a car."); } function Factory(entity, env, dependencies) { const instance = entity.bind(env, dependencies); return new instance(); } const pistons = Factory(Pistons, null, { log: console.log }); const wheels = Factory(Wheels, null, { log: console.log }); const engineDependencies = { pistons: pistons, log: console.log }; const engine = Factory(Engine, null, engineDependencies); const carDependencies = { wheels: wheels, log: console.log, engine: engine }; const car = Factory(Car, null, carDependencies); car.action();
Code of Conduct Report abuse