Last active
September 8, 2018 18:09
-
-
Save shannonmoeller/c1a0c1eae247e778827d1e2c68949576 to your computer and use it in GitHub Desktop.
Dependency-injection container example using vanilla JS.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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