The two child methods returned have access to the scope created by createFactories
, and thus the logger
that was passed in. It enables the logger
to be encapsulated within createFactories
' scope, which will remain after the function has been executed. However, we'll still have access to the logger reference through emailFactory
and smsFactory
.
Combining Closures and Dependency Injection

We'll create a factory function that accepts a logger and a starting value for a counter. It will return an object containing a decrementing counter function (minus
) and a logging factory (createFactories
), demonstrating both closures and dependency injection.
- The
CounterAndLoggerFactory
function encapsulates both a decrementing counter (using a closure) and a set of factories that use a logger (demonstrating dependency injection). - The
counter
variable is private and can only be accessed through theminus
function. - The
createFactories
function returns two factory functions that utilize the injectedlogger
. - The returned object allows access to both the
minus
function and thecreateFactories
function, enabling both decrementing counter functionality and logging functionality.
By combining closures and dependency injection in this way, the code snippet showcases the versatility and power of these concepts in JavaScript, allowing for modular, maintainable, and flexible design.
Complexity of Final Solution
O(1)
constant time & space complexity, this is a knowledge question!
xxxxxxxxxx
emailSender("John!"); // Logs: Hello, John!
function CounterAndLoggerFactory(startValue, logger) {
var counter = startValue;
var minus = function () {
counter -= 1;
return counter;
};
function createFactories() {
return {
emailFactory: function(greeting) {
return function(greet) {
logger(greeting + greet);
};
},
smsFactory: function(text) {
return function(text) { logger(text); };
}
};
}
return {
minus: minus,
createFactories: createFactories
};
}
// Usage Example:
var logger = console.log;