Share closure code (javascript)
<p>Is there any way to share code between two closures?</p>

<p>Example:</p>

<pre><code>// 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"
</code></pre>

<p>Here <code>getClosure1()</code> and <code>getClosure2()</code> return a closure that does similar tasks. I.e. both of them need to execute the <code>cbDoThing()</code> within a closure environment, but <code>getClosure2()</code> runs some other code in addition.</p>

<p>The above example does not work as wanted. <code>cbDoThing()</code> 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 <code>cbDoThing()</code>function in each closure.</p>

<p>PS: <a href="http://jsfiddle.net/9ZUpW/1/" rel="nofollow">JsFiddle playground</a>.</p>

<p><strong>EDIT</strong>: 
Now that I asked, an answer came to me with minor modifications:</p>

<pre><code>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);
    }
}
</code></pre>

<p>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.</p>

<p><a href="http://jsfiddle.net/9ZUpW/1/" rel="nofollow">JsFiddle</a> </p>
