1

[UPDATE] It turns out that I totally misunderstand scope of closure: The answer is here:

How do JavaScript closures work?

Example 7 answer my question, very helpful.

===================================================================

All:

I wonder how can I make a copy of a closure function like:

function closure(){
    var cv = "closure variable";
    function changecv(newcv){
        cv = newcv;
    }
    changecv.getcv = function(){return cv;}
    return changecv;
}

Say I have another function to duplicate this closure function:

function dupclosure(cFn){..... I do not know how to do this...}
var newclosureFn = dupclosure(closure);
var cf1 = closure();
var cf2 = newclosureFn ();
cf1("new closure variable");
console.log( cf2.getcv() );  // still "closure variable"

Thanks

Community
  • 1
  • 1
Kuan
  • 11,149
  • 23
  • 93
  • 201
  • 1
    `var cf2 = closure();` - http://jsfiddle.net/xskdamsp/ – Andreas Sep 14 '15 at 22:08
  • @Andreas Thanks. So if I want to share that cv variable and still with this closure function pattern, how can I do that? Using prototype(I thought prototype is only for object prototype chain, so I can not just use cv, I have to use closure.prototype.cv, right?)? – Kuan Sep 14 '15 at 22:44

0 Answers0