You cannot really cache a closure. If you do, then it still closes over the variables of the function it was first defined.
For example, you might consider doing this, which might look ok at a first glance:
var newUser = (function() {
var doSomethingCool;
function newUser(user){
doSomethingCool = doSomethingCool || function(){console.log(user);};
doSomethingCool();
}
return newUser;
}());
The first time we call newUser
, the doSomethingCool
function will be created. This is the output:
> newUser('foo')
foo
When we call the function a second time, the closure is reused. This is the output:
> newUser('bar')
foo
Why? Because the closure only closes of the variables of the function invocation it was defined in.
If you really want to "cache" the function, you have to parameterize it:
var newUser = (function() {
var doSomethingCool;
function newUser(user){
doSomethingCool = doSomethingCool || function(user){console.log(user);};
doSomethingCool(user);
}
return newUser;
}());
But I would not call this a closure. Technically it is a closure, but you don't make use of this property.
And actually, it is much easier then to write it like this:
var newUser = (function() {
var doSomethingCool = function(user){...};
function newUser(user){
doSomethingCool(user);
}
return newUser;
}());