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();
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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();