Skip to content

Instantly share code, notes, and snippets.

@shannonmoeller
Last active September 8, 2018 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shannonmoeller/c1a0c1eae247e778827d1e2c68949576 to your computer and use it in GitHub Desktop.
Save shannonmoeller/c1a0c1eae247e778827d1e2c68949576 to your computer and use it in GitHub Desktop.
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