One Pager Cheat Sheet
- A
closureinJavascriptis a feature that can be used to implementdependency injection, where a function can bepassed into 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 environmenteven 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
loggerremains encapsulated within the scope ofcreateFactoriesand is accessible through the two returned child methods,emailFactoryandsmsFactory, 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.
xxxxxxxxxx34
}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); }; },That's all we've got! Let's move on to the next tutorial.
If you had any problems with this tutorial, check out the main forum thread here.