1

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.

JsFiddle

4

1 回答 1

2

不错的作品。Javascript 只走原型链,这意味着 cbDoThing 没有引用或声明 closed1。在这种情况下,cbDoThing 只有一个原型——Object。如果没有显式地将参数传递给 cbDoThing,它将没有任何 closed1 的概念。

这是对 javascript 中闭包的彻底讨论:http: //jibbering.com/faq/notes/closures/

于 2012-09-04T14:36:28.570 回答