There is this 'store' variable where all the sessions are stored that I need to access only problem is that it's created within a function. There is another way i could access it but it's not really convenient
No there is no way to access store
without modifying the code. And you shouldn't modify the code of an external module, because store
is likely made inaccessible for a reason. Changing the code might result in a code base that would prevent you from updating the express-sessions
.
Having the need to do that sounds like an XY-Problem.
If it is your code and you want to allow the variable to be accessed there are different ways to do that. You for sure could move var num
outside of creatPrintNumFunction
(as described in the answer of alonealgorithm but that breaks the encapsulation you had before. Whether that is a good idea or not depends on the actual use case. But you need to be aware that if you do that that every "print" function returned from creatPrintNumFunction
then uses the same variable.
Let's say you don't want to move num
out of the scope of creatPrintNumFunction
because every "print" function returned from creatPrintNumFunction
should have its own num
variable.
What then you could do is to create another function (e.g. set
) within creatPrintNumFunction
that can change num
and assign this function as a property to the function you return from creatPrintNumFunction
.
function creatPrintNumFunction() {
var num = 12;
// both "set" and "printNum" create here
// have a closure over the same "num" variable
function set(val) {
num = val;
}
function printNum() {
console.log(num);
}
// the "set" function is assigned as a parameter to your
// printNum function
printNum.set = set;
return printNum;
}
var printerA = creatPrintNumFunction();
var printerB = creatPrintNumFunction();
printerA.set(13)
printerB.set(23)
printerA();
printerB();
The advantage of this approach is that you don't expose num
and you can control in your set
function how/if num
can be changed.