One Pager Cheat Sheet
- A
closure
inJavascript
is a feature that can be used to implementdependency injection
, where a function can bepassed in
to access certain variables or methods. - A closure is a combination of a function and a lexical environment in which it was declared, allowing the function to access its
lexical environment
even from outside of the outer function. - Dependency injection with closures can be used to reduce coupling between an object and its dependency, while allowing reconfiguration without changing existing business logic, as an alternative to using global context dependencies.
- The
logger
remains encapsulated within the scope ofcreateFactories
and is accessible through the two returned child methods,emailFactory
andsmsFactory
, all inO(1)
constant time and space complexity.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
34
}
var assert = require('assert');
/*
* Closures
*/
var minus = (function () {
var counter = 999;
return function () {
counter -= 1;
return counter;
};
})();
minus();
minus();
minus();
/*
* Dependency Injection With Closures
*/
function createFactories(logger) {
return {
emailFactory: function (greeting) {
return function (greet) {
logger(greeting + greet);
};
},
smsFactory: function (text) {
return function (text) {
logger(text);
};
},
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Alright, well done! Try another walk-through.
If you had any problems with this tutorial, check out the main forum thread here.