Is there any way to share code between two closures?
Example:
// ANTIPATTERN
var cbDoThing = function cbDoThing(arg){
return typeof closed1 +" " + arg;
}
function getClosure1(closed1) {
return cbDoThing;
}
function getClosure2(closed1) {
return function(arg) {
// do other work
return cbDoThing(arg);
}
}
f1 = getClosure1();
f1("ARG1"); // returns "undefined ARG1"
f2 = getClosure2();
f2("ARG2"); // returns "undefined ARG2"
Here getClosure1()
and getClosure2()
return a closure that does similar tasks. I.e. both of them need to execute the cbDoThing()
within a closure environment, but getClosure2()
runs some other code in addition.
The above example does not work as wanted. cbDoThing()
is defined in the global context, so closed1 variable is undefined. The wanted behavior is a pattern to make the closed1 variable be read from the closure scope chain, but without redefining the cbDoThing()
function in each closure.
PS: JsFiddle playground.
EDIT: Now that I asked, an answer came to me with minor modifications:
var cbDoThing = function cbDoThing(closed1, arg){
return closed1 +" " + arg;
}
function getClosure1(closed1) {
return function(arg) {
return cbDoThing(closed1, arg);
}
}
function getClosure2(closed1) {
return function(arg) {
// do other work
return cbDoThing(closed1, arg);
}
}
The cbDoThing does not access closed1 variable from the closure variable scope. Rather it is passed an extra argument. Then this function is called from each of the closures.