Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dependency-injection container example using vanilla JS.
let uid = 0;
class Foo {
constructor({ bar }, id) {
this.uid = uid++;
this.id = id;
this.bar = bar;
}
}
class Bar {
constructor({ baz }) {
this.uid = uid++;
this.baz = baz;
}
}
const container = {
// Class instances
foo(...args) {
return new Foo(container, ...args);
},
// Class singleton
get bar() {
return (this._bar ||
this._bar = new Bar(container)
);
},
// Pojo singleton
baz: {
uid: uid++,
bat: 'qux',
},
};
console.log('foo', container.foo('a'));
console.log('foo', container.foo('b'));
console.log('bar', container.bar);
console.log('bar', container.bar);
console.log('baz', container.baz);
console.log('baz', container.baz);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment